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文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM