Compile Angular 2 node_modules files into one file

2019-04-14 04:50发布

I am trying to figure out a way to compile everything I need from the angular 2 node_modules folder into one file.. It seems that there is a crazy amount of http calls when my site is loading and surely thats not optimal or the recommended process of the new and improved angular..

Im not concerned with my own typescript files as i know how to handle them but what are your approaches to concatenating the node_modules files etc ?

2条回答
太酷不给撩
2楼-- · 2019-04-14 05:16

If you're using SystemJS


1. package.json : add these to devDependencies

"devDependencies": {
    "gulp": "^3.9.1",
    "systemjs-builder": "^0.15.16"
  }

2. do npm install

3. create gulpfile.js at the same level of index.html, with this content in it

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


gulp.task('bundle-angular-dependencies', function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'systemjs.config.js');

  return builder
    .bundle('app/boot.js - [app/**/*.js]', 'path/to/put/angular.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});

4. open terminal and go to the directory of your project. do gulp bundle-angular-dependencies

5. Reference angular.bundle.js in your index.html, below system.js but above system.config.js.


If you have any queries, let me know.

查看更多
仙女界的扛把子
3楼-- · 2019-04-14 05:39

I've read through the github discussions about this and as far as I am aware there is no native bundling support, however I have created a gulp task that gets you 3/4 of the way there.

If you are using SystemJS, you can use the systemjs-builder package to bundle up all of angular 2's dependencies into one file. This file comes out at about 95k, which is quite reasonable; and as you probably guessed, load time goes down significantly (<1s). Note that Angular still tries to pull the custom packages (e.g. lodash/underscore) you have defined in the system-config file so I end up just copying these modules into the /dist folder with another gulp task (though you can do it manually if you are only bundling for production.)

This is a project in itself and if you started your project before the angular-cli came out, you will likely need to do heavy restructuring of your files to meet their standard directory structure.

The basic gist for the bundling gulp task is here: https://gist.github.com/stewhouston/27cac18c64d03b14de8b39389cbaa1c5. I have several other gulp tasks that are used in the bundling process and can paste them if you'd like, though if you can't write them yourself by that point the bundling process will be pretty excruciating.

Hopefully the angular 2 team release a native bundler soon to make this all unnecessary.

查看更多
登录 后发表回答