Search code examples
javascriptangularjsminifywebpack-2uglifyjs

Minification with AngularJS and Webpack 2


I want to concatenate a list of js files that contains my angularjs code and uglify it. I want to concatenate it in an ordered manner to avoid "that .... is not defined" errors.

I also have some libraries downloaded from github and placed in a "lib" folder. I want to concatenate those libraries in vendor.bundle.js.

This is the folder structure:

/app
    /feature1
        feature1.controller.js
    /feature2
        feature2.controller.js
    /...
    app.module.js
/libs
    /angular
        angular.min.js
    /angular-ui-router
        angular-ui-router.min.js
    /angular-material
        angular-material.min.js
        angular-material.min.css

    /...
app.js
vendor.js

Inside of app.js I have this:

require('./app/app.module.js');
require('./app/feature1/feature1.controller.js');
require('./app/feature2/feature2.controller.js');
...

Inside vendor.js I have this:

require('./libs/angular/angular.min.js');
require('./libs/angular-ui-router/angular-ui-router.min.js');
require('./libs/angular-material/angular-material.min.js');
require('./libs/angular-material/angular-material.min.css');
...

And this is the webpack.config.js:

const path = require('path');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    context: __dirname,
    entry: {
        app: "./app.js",
        vendor: "./vendor.js",
    },    
    output: {
        path: path.resolve(__dirname, "app"),
        filename: "app.bundle.js"
    },
    module: {
        rules: [
            {
              test: /\.css$/,
              use: [ 'style-loader', 'css-loader' ]
            }
          ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            filename:"./app/vendor.bundle.js"
        }),
        new UglifyJSPlugin({
            compress: true,
            sourceMap: false,
            mangle: true
        })
    ]
};

The result of this config is that the concatenation inside app.bundle.js is not ordered, so there are function not defined etc...

And the vendor.bundle.js is not created because it generate a lot of errors.

Which is the correct way to do the minification with splitted personal code and vendor code?


Solution

  • I solved this requiring files in a tree way. I used app.module.js as entry point, then in app.module.js I required the controller's files before injecting them. In this way webpack will require the files in the right order.