Angular 2 uses systemjs as the module loader to load user’s modules as well as the dependent libraries. It does not import all the dependencies into memory at the beginning but only loads one when it is needed. Whenever systemjs loads a module, it uses its config file to locate the path of the module and then initiate a XHR request to load it. The dynamic loading mechanism is very beneficial for developers because it allows them to only load the modified code. But it brings two problems in the production environment.
- The XHR requests create extra network traffic which may slow down the entire application especially for those who only have limited bandwidth.
- An Angular 2 application usually defines dozens of third party dependencies which internally may rely on other libraries. It is very difficult to make a proper and clean deployment.
To solve the problems, we would like to package the application along with all the dependencies to a single file and load it once in the index.html.
Preparation
- Install systemjs-builder
|
|
Install gulp
12npm install --global gulp-clinpm install gulp --save-devCreate a task in gulpfile.js as the following
Assume all the application codes are under “app” folder and the main entry file is main.js. The file systemjs.config.js is the config file for systemjs.12345678910111213var gulp = require('gulp');var Builder = require('systemjs-builder');gulp.task('app', function () {var builder = new Builder('.', './systemjs.config.js');builder.bundle('app/main.js', './dist/main-min.js', {minify: true, mangle: true}).then(function () {console.log('Build completed');}).catch(function (err) {console.log('Build failed');console.log(err);});});And run the task
1gulp app
It eventually generates a minified file main-min.js under the dist folder, we just inculde it in the index.html and it is good to go.
Sometimes, in order to speed up the build process, we want to create one package for the barely changed dependencies and another package for the frequently modified applications code respectively. So we need to split the above task into two tasks.