webpack多入口多出口(多端多應用)

多入口

  • 通過entry字段配置入口,例如
{
  page1: './src/page1.js',
  page2: './src/page2.js'
}

多出口,使用html-webpack-plugin,有多少的出口就配置實例化多少個,同時通過chunks字段表示將那些chunk引入

new HtmlWebpackPlugin({
      filename: 'page1.html',
      template: 'page1.html',
      inject: true,
      title: 'page1',
      chunks: ['page1','ventor'],
      templateParameters: {
        BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
      },
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
      }
    }),
    new HtmlWebpackPlugin({
      filename: 'page2.html',
      template: 'page2.html',
      inject: true,
      title: 'page2',
      chunks: ['page2','ventor'],
      templateParameters: {
        BASE_URL: config.build.assetsPublicPath + config.build.assetsSubDirectory,
      },
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
      }
    })

多出口的分包,主要藉助optimization.splitChunks

例如page1頁面使用vue、vuex、echart,page2應用使用了vue、vuex。

  1. 首先這兩頁面使用公共包有vue和vuex,所以這要拆分成公共包
  2. page1使用了echart,page2沒有使用,所以page2不要引入不相關的包
  3. 同時要結合html-webpack-plugin的chunks或者excludeChunks來表示包含或者排除那些chunk
  4. 最後就是要對runtime的js拆分,不同的出口引入不同runtime運行代碼,此處通過runtimeChunk設置爲true或則multiple,詳情可見webpack官網文檔
optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        ventor: {
          name: 'ventor',
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: 'initial' // 只打包初始時依賴的第三方
        },
        echart: {
          name: 'chunk-echart',
          test: /[\\/]node_modules[\\/]echart[\\/]/,
          priority: 20, // 權重要ventor的權重高,優先級要更高,不然就打到ventor裏面了
        }
      }
    },
    runtimeChunk: true,
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          mangle: {
            safari10: true
          }
        },
        sourceMap: config.build.productionSourceMap,
        cache: true,
        parallel: true
      })
    ]
  }

開發環境,config.dev.js配置

  1. 開發環境,只開放一個入口一個出口,通過入口配置文件來控制,例如:
module.exports = {
    page1: './src/page1.js',
    page2: './src/page2.js'
}
  1. 通過入口配置文件來控制出口,即控制實例化多少個html-webpack-plugin, 由於出口的html名字不同,所以要根據入口動態配置下devServer的首頁html, 即devServer.index = 'index.html' // 默認

借鑑的文檔

webpack

富圖團隊

知乎

分包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章