【发布时间】:2017-09-04 00:01:40
【问题描述】:
我花了一段时间用 angular 4 做 AOT,但总是得到这个错误: 未捕获的 ReferenceError:未定义要求
我收到此错误是因为我在我的应用程序中使用 jquery,并且在应用程序中,我有以下代码:
var jQuery = require('jquery');
jQuery("xxxx").val()
如果我删除它,整个 AOT 就会像魅力一样发挥作用。
我的 tsconfig-aot.json:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"lib": ["es5", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
"files": [
"src/app/app.module.ts",
"src/main.ts"
],
"angularCompilerOptions": {
"genDir": "aot",
"skipMetadataEmit" : true
}
}
还有我的汇总配置:
import rollup from 'rollup'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify'
export default {
entry: 'src/main.js',
dest: 'public/build.js', // output a single application bundle
sourceMap: false,
format: 'iife',
onwarn: function(warning) {
// Skip certain warnings
// should intercept ... but doesn't in some rollup versions
if ( warning.code === 'THIS_IS_UNDEFINED' ) { return; }
// intercepts in some rollup versions
if ( warning.indexOf("The 'this' keyword is equivalent to 'undefined'") > -1 ) { return; }
// console.warn everything else
console.warn( warning.message );
},
plugins: [
nodeResolve({jsnext: true, module: true}),
commonjs({
include: [ 'node_modules/rxjs/**','node_modules/jquery/**']
}),
uglify()
]
}
这是否意味着,如果您在 ng4 应用程序中使用 require(),那么 AOT 将无法工作?
感谢并希望听到您的建议。
我尝试使用这个: 从 'jquery' 导入 * 作为 jQuery; 然后它的工作方式与要求相同,并且在 JIT 模式下工作正常。而且,ngc 包也很好。但是当我使用汇总时,输出有这个错误:
???? Cannot call a namespace ('jQuery')
src/app/app.component.js (14:8)
12: }
13: AppComponent.prototype.ngOnInit = function () {
14: jQuery('h1').html('New Content');
^
15: };
16: return AppComponent;
这是更新的代码:
import * as jQuery from 'jquery';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./scss/app.component.scss']
})
export class AppComponent implements OnInit{
ngOnInit(){
jQuery('h1').html('New Content');
}
}
有什么想法吗?
【问题讨论】:
-
您不应该将
require与--module es2015一起使用,这将导致TypeScript 编译错误。它没有的唯一原因是您使用的是var..require表单,而不是 TypeScript 中正确的import..require表单。由于前面提到的原因,它仍然不正确。尝试import jQuery from 'jquery';,如果在运行时抛出未定义jQuery,请尝试import * as jQuery from 'jquery';
标签: angular angular2-aot