我正在尝试构建包含一些具有动态导入功能的组件的项目,例如:
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 || {})
}
}
Run Code Online (Sandbox Code Playgroud)
在构造函数上的动态导入似乎是问题所在。我收到以下错误:
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();
| });
Run Code Online (Sandbox Code Playgroud)
据我研究,从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"
]
}
Run Code Online (Sandbox Code Playgroud)
这是其中的内容 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/*"]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的打字稿版本是~3.1.6。
简而言之:
它是由引起的NPM问题出现了@angular-devkit/build-angular更新的0.12.x,以0.13.x从引擎盖下相关的WebPack更新4.28.x到4.29.x。
可能的解决方案(解决方法):
@angular-devkit/build-angular0.12.xacorn依赖项(例如,在撰写本文时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和发现的问题(13767,13793)在角CLI,它出人意料地被关闭。但是,发行号13793中的alan-agius4 评论为真正的起源提供了一些启示:对等物依赖关系的无效吊装;sokra 在此评论中详细解释了。
问题#4794已经接受了请求#147,但随后在请求#152中被还原,在编写本文时,问题#4794仍处于打开状态。
你不能就import这样打电话。您需要SystemJS先导入。然后调用它的import方法。
import('jquery-knob').then(()=>{
this.render()
})
Run Code Online (Sandbox Code Playgroud)
stackblitz:https://stackblitz.com/edit/angular-bkbqkj
| 归档时间: |
|
| 查看次数: |
2041 次 |
| 最近记录: |