问题
I have an angular-cli app,
npm -v 3.10.8
node -v v6.9.1
angular2 ^2.4.0
angular/cli 1.0.0-beta.32.3
when I add to package.json this
"angular2-auto-scroll": "1.0.12"
angular2-auto-scrol website
and in app.module.ts import it
import { Angular2AutoScroll } from "angular2-auto-scroll/lib/angular2-auto-scroll.directive";
and add it to declarations section ng build --prod fails with this error
ERROR in Unexpected value 'Angular2AutoScroll in C:/coding/workspace/myapp/myapp-web/node_modules/angular2-auto-scroll/lib/angular2-auto-scroll.directive.d.ts' declared by the module 'AppModule in C:/coding/workspace/myapp/myapp-web/app_code/app/app.module.ts'
ERROR in ./app_code/main.ts Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'C:\coding\workspace\myapp\myapp-web\app_code'
@ ./app_code/main.ts 6:0-74
@ multi ./app_code/main.ts
however when I build with just ng build without --prod then all build fine. Does anyone know what could be the reason? Or any other way I can import this npm package so it does not fail PROD build?
回答1:
The issue is with AOT compilation. AOT happens by default when using --prod
flag.
take a look at the source code for angular2-auto-scroll That project defines one TS file in the src/angular2-auto-scroll.directive.ts
If you look at the tsconfig.js file specifically "module": "commonjs"
. you'll see that the module this directive transpiles to is commonjs
If you look in your project under C:/coding/workspace/myapp/myapp-web/node_modules/angular2-auto-scroll/lib/
you'll see a TS type definition .d.ts
, a .js
and a .map
file. the js file is a commonjs
module.
AOT does not like commonjs
modules, you can research that on your own, it needs either an es5
or es6
module.
All that said, here are some options to fix it
- Copy the directive TS file from the source github angular2-auto-scroll.directive.ts to your prject and remove the dependency.
- or you can make a pull request to the repo asking to change the
"module": "commonjs"
to"module": "es6"
note: I opened an issue for it here - or if you do not care for aot, (which is highly recommended btw), you can cancel it by running
build
command with--aot=false
read here on build options
hope this helps.
Resources on AOT: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html https://github.com/angular/angular-cli/issues/1732
来源:https://stackoverflow.com/questions/43166491/angular2-build-under-angular-cli-with-directive-and-ng-build-prod