Friday, 17 March 2017

how to chunk the bundle.js file

I have created a project using react and flux architecture. Need to chunk the bundle.js file because by combining all the files it is creating a huge js file of 4mb which is causing problem in downloading on slow network so how to chunk the js file so that only the required libraries are included when a page opens

my directory structure is

enter image description here

webpack.config.js file

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'cheap-module-source-map',
  entry: [
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: ''
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      // names: ["app", "subPageA"]
      // (choose the chunks, or omit for all chunks)

      children: true,
      // (use all children of the chunk)

      async: true,
      // (create an async commons chunk)

      // minChunks: 3,
      // (3 children must share the module before it's separated)
    })
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'src')
    }, {
      test: /\.css$/,
      exclude: /\.useable\.css$/,
      loader: "style-loader!css-loader"
    }, {
      test: /\.useable\.css$/,
      loader: "style-loader/useable!css-loader"
    }, {
      test: /\.png$/,
      loaders: ["url-loader?mimetype=image/png"]
    }, {
      test: /\.(png|woff|woff2|eot|ttf|svg)$/,
      loader: 'url-loader?limit=100000'
    }]
  }
};

server.js file

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true
}).listen(3000, 'localhost', function(err, result) {
    if (err) {
        return console.log(err);
    }

    console.log('Listening at http://localhost:3000/');
});

index.html file

<html>

<head>
  <title>Project</title>
</head>

<body>
  <div id="app" />
  <script src="bundle.js" type="text/javascript"></script>
</body>

</html>


via Gagan

No comments:

Post a Comment