[英]Dynamic import on Angular 7+
我正在尝试构建包含一些具有动态导入的组件的项目,例如:
import {Directive, Input, ElementRef} from '@angular/core';
@Directive({
selector: '[saKnob]'
})
export class KnobDirective {
@Input() saKnob: any;
constructor(private el: ElementRef) {
import('jquery-knob').then(()=>{
this.render()
})
}
render(){
$(this.el.nativeElement).knob(this.saKnob || {})
}
}
构造函数上的动态导入似乎是问题所在。 我收到以下错误:
ERROR in ./src/app/shared/forms/input/knob.directive.ts 15:8
Module parse failed: 'import' and 'export' may only appear at the top level
(15:8)
You may need an appropriate loader to handle this file type.
| var _this = this;
| this.el = el;
> import('jquery-knob').then(function () {
| _this.render();
| });
据我研究,从 Angular 4 开始就支持这种导入,我使用的是 Angular 7。
有没有人知道可能是什么问题?
* 更新 *
正如一些答案所指出的,我已经在我的tsconfig.app.file
文件中使用了 esnext:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "esnext",
"types": [],
"paths": {
"@app/*": ["app/*"],
"@env/*": ["environments/*"]
}
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}
这是tsconfig.json
的内容
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "es2015",
"target": "es5",
"typeRoots": ["node_modules/@types"],
"lib": ["es2018", "dom"],
"paths": {
"@app/*": ["src/app/*"],
"@env/*": ["src/environments/*"]
}
}
}
我的打字稿版本是~3.1.6
。
简而言之:
它是由引起的NPM问题有出现了@angular-devkit/build-angular
更新从0.12.x
到0.13.x
引擎盖下和相关的WebPack更新从4.28.x
到4.29.x
。
可能的解决方案(变通方法):
@angular-devkit/build-angular
devkit @angular-devkit/build-angular
0.12.xnpm i --save acorn
是添加明确的最新acorn
依赖项(例如npm i --save acorn
在撰写本文时将添加6.1.1
)。 另一种流行的解决方法是运行npm update acorn --depth 20 && npm dedupe
。细节:
最近在项目从 Angular 7.2 更新到 Angular 7.3 后偶然发现了类似的问题。 在更新构建之前很好,并且esnext
作为target
已经在tsconfig.json
指定。
经过一些测试,我发现它与@angular-devkit/build-angular
并发现 angular-cli 中的问题( 13767 、 13793 )出人意料地关闭了。 但alan-agius4 在 issue 13793 中的评论揭示了真正的起源:对等依赖的无效提升; sokra 在此评论中详细解释了。
问题 #4794 的拉取请求 #147 已经被接受,但随后它在拉取请求 #152 中恢复,并且在撰写本文时问题 #4794 仍处于打开状态。
你不能就这样调用import
。 您需要先导入SystemJS
。 然后调用它的import
方法。
import('jquery-knob').then(()=>{
this.render()
})
堆栈闪电战: https ://stackblitz.com/edit/angular-bkbqkj
它在使用ng new
和最新的 angular-cli 创建新项目时有效。
我认为问题在于您的 Typescript 配置。 尝试在您的tsconfig.json
设置这些值:
{
...
"module": "es2015",
"target": "es5",
"lib": [
"es2018",
...
]
}
这在 Angular 8 上对我有用。首先安装 acorn(acorn 将添加到 package.json 文件中)然后删除 node_modules 和 package-lock.json 然后 npm install。
npm install acorn
rm -rf node_modules
rm -f package-lock.json
npm install
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.