I spent quire a while to do AOT with angular 4, and always got this error: Uncaught ReferenceError: require is not defined
I got this error because I am using jquery in my app, and in the application, I am having this code:
var jQuery = require('jquery');
jQuery("xxxx").val()
If I remove this, the whole AOT worked like a charm.
My 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
}
}
And my rollup config:
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()
]
}
Does this mean, if you are using require() inside your ng4 app, then AOT will not work?
Thanks and hope to hear your advice.
I tried to use this: import * as jQuery from 'jquery'; Then it worked same as require, and in JIT mode, it worked fine. And also, ngc package is fine. But when I use roll-up, the out put has this error:
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;
This is updated code:
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');
}
}
Any idea?