0

I am converting my angular2 app in aot compilation, We have around 8 modules and each modules have an average of 10-12 components. When i am creating build for prod, its generating 53mb of app.bundle.js file. This is really huge. According to me, it including the all node_modules files.

My tsconfig-aot.json

{


"compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es2015", "dom"],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "skipLibCheck": true
  },
  "angularCompilerOptions": {
   "genDir": "aot",
   "skipMetadataEmit" : true,
   "entryModule": "src/app/app.module#AppModule"
 },
  "exclude": [
    "node_modules/*",
    "aot/"
  ]
}

and my webpack-prod.config.js

// Helper: root() is defined at the bottom
const path = require('path');
const webpack = require('webpack');
const ngToolsWebpack = require('@ngtools/webpack');
// Webpack Plugins
const CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
const autoprefixer = require('autoprefixer');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');



/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
const ENV = "build";

console.log(`ENV variable is ${ENV}`);

module.exports = function makeWebpackConfig() {

    var config = {};
    config.devtool = 'cheap-module-eval-source-map';
    config.cache = false;
    //config.debug = true; this option ain't working!!
    config.entry = {
        'polyfills': './src/polyfills.ts',
        'vendor': './src/vendor.ts',
        'app': './src/main.ts' // our angular app
    };
    config.output = {
        path: root('dist'),
        publicPath : '/',
        filename: 'js/[name].[hash].bundle.js',
        chunkFilename: '[id].[hash].chunk.js',
        sourceMapFilename: 'js/[name].[hash].bundle.map',
    };
    config.resolve = {
        // only discover files that have those extensions
        extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
    };

    config.stats = {
        colors: true,
        reasons: true,
        errorDetails: true
    };

    config.module = {
        rules: [
             {
                test: /pnotify.*\.js$/,
                loader: "imports-loader?define=>false,global=>window,this=>window"
            },
            // Support for .ts files.
            {
                test: /\.ts$/,
                loaders: ['@ngtools/webpack', 'angular2-template-loader', '@angularclass/hmr-loader','angular-router-loader'],
               // include : ['/aot/node_modules'],
               // exclude: /node_modules/
            },

            // copy those assets to output
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'file-loader?name=[path][name].[hash].[ext]?'
            },

            // Support for *.json files.
            {
                test: /\.json$/,
                loader: 'json-loader'
            },

            // Support for CSS as raw text
            // use 'null' loader in test mode (https://github.com/webpack/null-loader)
            // all css in src/style will be bundled in an external css file
            {
                test: /\.css$/,
                exclude: root('src', 'app'),
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader','postcss-loader']
                })
            },
            // all css required in src/app files will be merged in js files
            {
                test: /\.css$/,
                include: root('src', 'app'),
                loader: 'raw-loader!postcss-loader'
            },

            // support for .scss files
            // all css in src/style will be bundled in an external css file
            {
                test: /\.scss$/,
                exclude: root('src', 'app'),
                loader: ExtractTextPlugin.extract({
                    fallbackLoader: 'style-loader',
                    loader: ['css-loader?sourceMap','postcss-loader','sass-loader?sourceMap']
                })
            },
            // all css required in src/app files will be merged in js files
            {
                test: /\.scss$/,
                include: root('src', 'app'),
                loader: 'raw-loader!postcss-loader!sass-loader'
            },

            // support for .html as raw text
            // todo: change the loader to something that adds a hash to images
            {
                test: /\.html$/,
                loader: 'raw-loader',
                exclude: [root('src/index.html')]
            },


        ]
    };


    /**
     * Plugins
     * Reference: http://webpack.github.io/docs/configuration.html#plugins
     * List: http://webpack.github.io/docs/list-of-plugins.html
     */
    config.plugins = [
        // Define env variables to help with builds
        // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
        new webpack.DefinePlugin({
            // Environment helpers
            'process.env': {
                ENV: JSON.stringify(ENV)
            }
        }),
        new ngToolsWebpack.AotPlugin({
            tsConfigPath: './tsconfig-aot.json',
            entryModule: root('src/app/app.module#AppModule')
           // exclude:'./node_modules',
        }), 
        // Workaround needed for angular 2 angular/angular#11580
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            root('./src') // location of your src
        ),

        // Tslint configuration for webpack 2
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: [
                    autoprefixer({
                        browsers: ['last 3 version']
                    })
                ],
                sassLoader: {
                    includePaths: [path.resolve(__dirname, 'src')]
                },
                context: '/'
            },
            debug: true
        }),

        // Generate common chunks if necessary
        // Reference: https://webpack.github.io/docs/code-splitting.html
        // Reference: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
        new CommonsChunkPlugin({
            name: ['vendor', 'polyfills'],
            minChunks: Infinity
        }),

        // Inject script and link tags into html files
        // Reference: https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
            template: './src/index.html',
            chunksSortMode: 'dependency'
        }),

        // Extract css files
        // Reference: https://github.com/webpack/extract-text-webpack-plugin
        new ExtractTextPlugin({
            filename: 'css/[name].css',
            disable: false,
            allChunks: true
        }),

         new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery',
            'window.jQuery': 'jquery',
            'PNotify' : 'pnotify',
            "Tether": 'tether',
            "window.Tether": "tether"
        }),


         // Production specific plugins


         new webpack.NoErrorsPlugin(),

         new webpack.optimize.UglifyJsPlugin({
              sourceMap: true,
            //   mangle  : true,
              compress: {
                // sequences   : true,
                // dead_code   : true,
                // conditionals: true,
                // booleans    : true,
                // unused      : true,
                // if_return   : true,
                // join_vars   : true,
                drop_console: true,
                // warnings: false
            }
        }),

        new CopyWebpackPlugin([
            {
              from: 'src/assets',
              to: 'assets'
            },
            {
              from: 'src/favicon.ico',
            },
            {
              from: 'src/login.html',
            },
            {
              from: 'src/login.js',
            },
            {
              from: 'src/shim.min.js',
            },
            {
              from: 'src/nprogress.js',
            }
        ]),
    ];



    /**
     * Dev server configuration
     * Reference: http://webpack.github.io/docs/configuration.html#devserver
     * Reference: http://webpack.github.io/docs/webpack-dev-server.html
     */
    config.devServer = {
        historyApiFallback: true,
        stats: 'normal' // none (or false), errors-only, minimal, normal (or true) and verbose
    };

    return config;
}();

// Helper functions
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

Please help me this

  • 1
    One of the features of Angular 4 is that the weight of the generated code gets 60% lighter, more or less. So migrating to Angular4 would be a first step in my opinion. Check it out: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html – SrAxi Apr 20 '17 at 13:25
  • You probably also want to incorporate gzipping for the copied assets, since the compression plugin doesn't handle those. https://gist.github.com/nitind/a3d7932ed118fb2cf7b7208df8e6f1c8 – nitind Apr 20 '17 at 13:44
  • @nitind yes i will do the gzipping. but 53 mb is really huge. according to me bundle.js containing the data of node_modules that's why its huge. is it supposed contain data of node_modules? – Avilash Choudhary Apr 21 '17 at 06:30
  • can you check what is size of polyfills and vendor separately ? – sandyJoshi Apr 25 '17 at 10:31

0 Answers0