简体   繁体   中英

(Angular2 RC5) How to create a bundle for each module using SystemJS that can be lazily loaded by the router?

I'm converting my Angular2 RC5 app to use the router . I am also compiling ahead-of-time using the Angular2 compiler (ngc), then concatenating and minifying the App files into a bundle.min.js, and the external libraries into a separate 'vendor' file. I am using the Browserify 'standalone' option to create a UMD bundle, then just including it in index.html with the script tag. I'm able to leave out the "System.import('app').catch(...)" script this way.

Now I want to lazily load an Angular2 module while still serving my app in bundles to reduce load time. I can get lazy loading to work without bundling my code in a development build, but when creating a production build with bundling & minification I don't know how to get it to work.

It looks like I need to use SystemJS builder to create bundles (presumably one per module). I don't know where to go from there though.

Any assistance is much appreciated.

I can offer general outline here.

npm install systemjs-builder

Create a bundle for the module. In the simplest case, let's assume that all typescript is transpiled already and you don't need to run typescript compiler at build time (otherwise you will need to install and configure systemjs plugin for typescript )

The following build.js file does the job for the Angular 2 quickstart tutorial:

var Builder = require('systemjs-builder');

var builder = new Builder;

builder.loadConfig('systemjs.config.js').then(function() {

    builder.bundle('app/app.module.js', 'app/app.module.bundle.js', {minify: false});

});

You might want to take a look at generated app.module.bundle.js to see if there is some dependency which is already included in some other bundle - then you need to exclude it from the build, either in systemjs.config.js or in your build.js, in the latter for example (after main config is loaded):

bulider.loader.config({meta: {'module-name': {build: false}});

Then, for lazy loading, you need to tell SystemJS to load the bundle (and register all modules within) when the first module from the bundle needs to be imported. According to the documentation , this is how to do it in systemjs.config.js (not tested):

System.config({
  bundles: {
    'path-to-bundle': ['module1', 'module2']
  }
});

What I'm not sure here is whether module names must match the names used in System.registerDynamic calls in the bundle, or names that you use to import them in your source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM