Webpack bundles my files in the wrong order (CommonsChunkPlugin)

后端 未结 4 1849
一生所求
一生所求 2020-12-03 03:04

What I want is to bundle my JavaScript vendor files in a specific order via CommonsChunkPlugin from Webpack.

I\'m using the CommonsChunkPlugin

4条回答
  •  悲&欢浪女
    2020-12-03 03:24

    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!

提交回复
热议问题