Simple solution to share modules loaded via NPM across multiple Browserify or Webpack bundles

后端 未结 3 1109
Happy的楠姐
Happy的楠姐 2021-02-04 05:36

Pulling my hair out here looking for a simple solution to share code, required via NPM, across multiple Browserify or Webpack bundles. Thinking, is there such a thing

3条回答
  •  囚心锁ツ
    2021-02-04 05:55

    With webpack you'd use multiple entry points and the CommonChunkPlugin.

    Taken from the webpack docs:


    To split your app into 2 files, say app.js and vendor.js, you can require the vendor files in vendor.js. Then pass this name to the CommonChunkPlugin as shown below.

    module.exports = {
      entry: {
        app: "./app.js",
        vendor: ["jquery", "underscore", ...],
      },
      output: {
        filename: "bundle.js"
      },
      plugins: [
        new webpack.optimize.CommonsChunkPlugin(
            /* chunkName= */"vendor",
            /* filename= */"vendor.bundle.js"
        )
      ]
    };
    

    This will remove all modules in the vendor chunk from the app chunk. The bundle.js will now contain just your app code, without any of it’s dependencies. These are in vendor.bundle.js.

    In your HTML page load vendor.bundle.js before bundle.js.

    
    
    

提交回复
热议问题