webpack多页面打包

在src下新建多个js文件和html模板:

在entry里配置多个入口文件

  entry: {
    index: './src/index.js',
    list: './src/list.js',
  },

HtmlWebpackPlugin里配置不同的html页面引用不同的js文件

const plugins = [
  new HtmlWebpackPlugin({
    template: './src/index.html',//使用模板index.html
    filename: 'index.html',//打包生成的文件名叫index.html
    chunks:['index']//index.html里引用打包生成的index.js
  }),
  new HtmlWebpackPlugin({
    template: './src/list.html',
    filename: 'list.html',
    chunks:["list"]
  })
]

但是每次在 entry里新加一个入口,就多加一个HtmlWebpackPlugin比较麻烦,所以我吗可以写个函数,动态生成plugins。

const makePlugins = (config) => {
  //其它plugins
  let plugins = [
    new CleanWebpackPlugin(),
    new BundleAnalyzerPlugin(),
    new webpack.ProvidePlugin({
      _: 'lodash'
    }),
  ]
  //根据entry生成new HtmlWebpackPlugin
  Object.keys(config.entry).forEach(item => {
    plugins.push(
      new HtmlWebpackPlugin({
        template: `./src/${item}.html`,
        filename: `${item}.html`,
        chunks: [`${item}`]
      })
    )
  })
  //根据dll.js生成new AddAssetHtmlWebpackPlugin
  //根据manifest.json生成new DllReferencePlugin
  files.forEach(file => {
    if (/.*\.dll.js/.test(file)) {
      plugins.push(new AddAssetHtmlWebpackPlugin({//将打包好的dll文件挂载到html中
        filepath: path.resolve(__dirname, '../dll', file)
      }))
    }
    if (/.*\.manifest.json/.test(file)) {
      plugins.push(new webpack.DllReferencePlugin({//分析第三方模块是否已经在dll文件里,如果里面有就不用再node_modules在分析打包了
        manifest: path.resolve(__dirname, '../dll', file)
      }))
    }
  })
  return plugins;
}
commonConfig.plugins = makePlugins(commonConfig);

总结:多页面需要我们做的就是,在entry里配置多个入口文件,在HtmlWebpackPlugin里配置不同的html页面引用不同的js文件。

posted @ 2020-09-10 10:36  哥哦狗子  阅读(1259)  评论(0编辑  收藏  举报