我在组件中使用System
。
export class LoginComponent {
constructor() {
System.import('app/login/login.js');
}
}
文件加载正常,但 TypeScript 编译器说
Error:(10, 9) TS2304: Cannot find name 'System'.
我的浏览器控制台说
EXCEPTION: Error: Uncaught (in promise): Error: Error: http://localhost:3000/app/login/login.js detected as register but didn't execute.
at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:332:29)
at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:2111:31)
at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:331:35)
at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:227:44)
Error loading http://localhost:3000/app/login/login.js
Error: Uncaught (in promise): Error: Error: http://localhost:3000/app/login/login.js detected as register but didn't execute.(…)
我该如何解决这个问题?
您有一个错误,因为您没有 SystemJS 库的类型。
大多数时候,我们不会在 TypeScript 文件中显式使用System.import
,因为我们可以让它在后台运行。我的意思是,当您使用以下方法时,TypeScript 编译器会将导入转换为 SystemJS 支持的内容:
import {...} from 'app/login/login';
export class LoginComponent {
constructor() {
}
}
您可以注意到我删除了js
扩展,因为 SystemJS 允许配置解析模块时要添加的默认扩展:
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
如何使用 ES6 语法导入我的.js文件
两步:
-
在
vendor.d.ts
中声明 JS 文件声明模块"应用程序/登录/登录" { var foo:any; 导出 = FOO;}
-
在你的打字稿中使用它
从"应用程序/登录/登录"导入 * 作为登录名;
现在只需使用"--模块系统"🌹编译代码