Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering multiple entry points in Webpack

I have multiple entries in my Webpack config:

entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},

When I run npm start (webpack-dev-server --inline --progress --port 8080 --bail) the \<my-app>Loading...</my-app> in my index.html turns into scripts in this order:

<script type="text/javascript" src="http://localhost:8080/common.js"> <!--I also have CommonsChunkPlugin-->
</script><script type="text/javascript" src="http://localhost:8080/vendor.js"></script>
<script type="text/javascript" src="http://localhost:8080/polyfills.js"></script>
<script type="text/javascript" src="http://localhost:8080/app.js"></script>

But when I run webpack -p --progress --profile --bail it's in this order:

common, app, polyfil, then vendor

Order is important. My app.js code won't work if run before polyfil.js or vendor.js. How do I control the order?

like image 789
Nathan Cooper Avatar asked Oct 06 '16 15:10

Nathan Cooper


Video Answer


2 Answers

You can use the 'manual' option these days :

new HtmlWebpackPlugin({
    chunks: ['polyfill', 'vendor', 'bundle'],
    chunksSortMode: 'manual',
}),
like image 158
jony89 Avatar answered Sep 16 '22 23:09

jony89


You can create a helper in order to accomplish it:

function packageSort(packages) {
    // packages = ['polyfills', 'vendor', 'app']
    var len = packages.length - 1;
    var first = packages[0];
    var last = packages[len];
    return function sort(a, b) {
      // polyfills always first
      if (a.names[0] === first) {
        return -1;
      }
      // app always last
      if (a.names[0] === last) {
        return 1;
      }
      // vendor before app
      if (a.names[0] !== first && b.names[0] === last) {
        return -1;
      } else {
        return 1;
      }
    }
  }

And in your webpack config file:

plugins.index = new HtmlWebpackPlugin({
  template:       'src/index.html',
  filename:       'index.html',
  chunksSortMode: packageSort(['polyfills', 'vendor', 'app'])
});
like image 33
Edmar Miyake Avatar answered Sep 19 '22 23:09

Edmar Miyake