4

I am encountering a couple issues wrt getting AoT working in Angular 5 using Webpack. The Webpack AoT build completes without errors.

1) Code splitting due to lazily loaded modules is not happening when using @ngtools/webpack AngularCompilerPlugin. When using the standard Angular/TS non-AoT loaders (see commented rules in the webpack config below), I correctly get separate bundles generated for each lazy route. However using the AngularCompilerPlugin, no bundles corresponding to lazily loaded modules are generated. See the relevant file content below. What am I missing??

Package versions:

"@angular/cli": "1.6.3",
"@angular/compiler-cli": "5.1.3",
"@angular/language-service": "4.4.6",
"@ngtools/webpack": "1.9.3",
"@types/core-js": "0.9.34",
"webpack": "3.10.0",
"@angular/animations": "5.1.3",
"@angular/common": "5.1.3",
"@angular/compiler": "5.1.3",
"@angular/compiler-cli": "5.1.3",
"@angular/core": "5.1.3",
"@angular/forms": "5.1.3",
"@angular/http": "5.1.3",
"@angular/platform-browser": "5.1.3",
"@angular/platform-browser-dynamic": "5.1.3",
"@angular/platform-server": "5.1.3",
"@angular/router": "5.1.3",

Webpack config:

const webpack = require('webpack');
const helpers = require('./helpers');

const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;

module.exports = function(options) {
    return {
        entry: {
            app: './app/main.ts',
            vendor: './app/vendor.ts'
        },

        output: {
            publicPath: '/app/dist/bundles/',
            path: helpers.root('./dist/bundles'),
            filename: '[name].js',
            sourceMapFilename: '[name].map',
            chunkFilename: '[name].chunk.js'
        },

        resolve: {
            extensions: ['.ts', '.js'],
            modules: [helpers.root('node_modules'), helpers.root('libs')]
        },

        module: {
            rules: [
                //{
                //    test: /\.ts$/,
                //    loaders: [
                //        'awesome-typescript-loader',
                //        'angular-router-loader',
                //        'angular2-template-loader',
                //        'source-map-loader'
                //    ]
                //},
                {
                     test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
                     loader: '@ngtools/webpack',
                },
                {test: /\.css$/, loaders: ['to-string-loader', 'css-loader']},
                {test: /\.htm(l)*$/, loader: 'raw-loader'},
                {test: /\.(eot|svg|cur)$/, loader: 'file-loader?name=[name].[hash:20].[ext]'},
                {
                    test: /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
                    loader: 'url-loader?name=[name].[hash:20].[ext]&limit=10000'
                }
            ]
        },

        plugins: [
            // Workaround for angular/angular#11580
            new ContextReplacementPlugin(
                /**
                 * The (\\|\/) piece accounts for path separators in *nix and Windows
                 */
                /\@angular(\\|\/)core(\\|\/)esm5/,
                helpers.root('app'), // location of your src
                {
                    /**
                     * Your Angular Async Route paths relative to this root directory
                     */
                }
            ),

            new AngularCompilerPlugin({
                tsConfigPath: helpers.root('tsconfig.json'),
                entryModule: helpers.root('app/app.module') + '#AppModule',
                sourceMap: true
            }),

            new CommonsChunkPlugin({
                name: ['vendor', 'bootstrap'],
                minChunks: 2
            })

        ],

        node: {
            global: true,
            crypto: 'empty',
            process: true,
            module: false,
            clearImmediate: false,
            setImmediate: false
        }
    };
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "typeRoots": [
      "./node_modules/@types/"
    ],
    "lib": [
      "es6",
      "dom"
    ]
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules/*"
  ],
  "angularCompilerOptions": {
    "preserveWhitespaces": false
  }
}

app.routes.module.ts

...
export const EVENTS_GUARD_TOKEN = new InjectionToken('events-access.guard');

const routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'admin', loadChildren: './admin/admin.module#AdminModule'},
    {path: 'application', loadChildren: './curated-views/application/application.module#ApplicationModule'},
    {path: 'demo', loadChildren: './demo/demo.module#DemoModule'},
    {path: 'events', loadChildren: './events/events.module#EventsModule', canLoad: [EVENTS_GUARD_TOKEN]},
    ...
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    providers: [
        RouteAccessGuardProvider(EVENTS_GUARD_TOKEN, FEATURE_EVENTS)
    ]
})
export class AppRoutesModule {}

2) My other issue is that when trying to run the resulting AoT build, I get the following runtime error:

Error message

The error itself (and the code it references) seems to be a red herring, however the error prevents the app from loading.

I'm completely stuck at this point. Please help! :)

user3481798
  • 247
  • 2
  • 11
  • 1
    I haven't been using webpack separatly as it is like this, since I've always been using `Angular-CLI ` to do that for me, but you could use it just to try that the lazy-loading and AoT is working fine by itself. You will know this is coming from the Webpack configuration like that. Good luck – Alex Beugnet Jan 12 '18 at 16:52
  • Thanks for the suggestion. Will try that. – user3481798 Jan 12 '18 at 19:35
  • I had this and it was a circular depency issue – The Segfault Jun 20 '18 at 11:04

0 Answers0