Webpack bundles my files in the wrong order (CommonsChunkPlugin)

混江龙づ霸主 提交于 2019-11-27 22:50:17

You can try https://webpack.js.org/guides/shimming/#script-loader - it looks like it will execute scripts in order and in global context.

Ollie Cee

Success!

webpack.config.js

module.exports = {
  entry: {
    app: './app.jsx',
    vendor: [
        "script-loader!uglify-loader!jquery",
        "script-loader!uglify-loader!tether",
        "script-loader!uglify-loader!bootstrap",
        "script-loader!uglify-loader!wowjs",
    ]
  },

  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js',
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        filename: 'vendor.bundle.js'
    }),

    new webpack.optimize.UglifyJsPlugin(),
  ],
};

What magic is happening here?

  1. Webpack creates vendor.bundle.js by minifying & bundling my vendor files which now execute in the global context.
  2. Webpack creates bundle.js with all of its application code

entry file (app.jsx in this case)

import './script';

This script is just custom JavaScript that uses jQuery, Bootstrap, Tether and wowjs. It executes after vendor.bundle.js, allowing it to run successfully.

A mistake I made trying to execute my script.js was that I thought it had to be in the global context. So I imported it with script-loader like this: import './script-loader!script';. In the end, you don't need to because if you're importing through your entry file it will end up in the bundle file regardless.


Everything is all good.

Thanks @Ivan for the script-loader suggestion. I also noticed that the CommonsChunkPlugin was pulling the non-minified vendor versions so I chained uglify-loader into the process.

Although, I do believe some .min.js are created differently to get rid of extra bloat. Though that is for me to figure out. Thanks!

Worked with htmlWebpackPlugin from official tutorials and switched the order form entry key. ( vendor then app )

In webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
      vendor: [
          'angular'
      ],
      app: [
          './src/index.js',
          './src/users/users.controller.js',
          './src/users/users.directive.js',
      ]
  },
   plugins: [
       new CleanWebpackPlugin(['dist']),
       new HtmlWebpackPlugin({
           template: './src/index-dev.html'
       }),
       new webpack.NamedModulesPlugin()
  ...
}

Now in the generated index.html file I have the correct order

<script src='vendor.bundle.js'></script>
<script src='app.bundle.js'></scrip
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!