webpack進階--02--多頁面應用配置

項目文件結構:

├─build
├     ├─webpack.base.js
├     ├─webpack.dev.js
├     └─webapck.prod.js
├─package.json
├
├─src
    └─views
          ├─admin
          ├     ├─index.js
          ├     └─index.html
          └─client
                ├─index.js
                └─index.html

entry配置

開發環境(dev):

entry: {
    admin: [
      resolve('./src/views/admin/index.js'),
      'webpack-hot-middleware/client?quiet=true' // 如果是通過webpack-hot-middleware啓動熱更新的,需要加上熱更新的客戶端
    ],
    client: [
      resolve('./src/views/client/index.js'),
      'webpack-hot-middleware/client?quiet=true' // 如果是通過webpack-hot-middleware啓動熱更新的,需要加上熱更新的客戶端
    ]
  }

生產環境(prod):

entry: {
    admin: [
      resolve('./src/views/admin/index.js')
    ],
    client: [
      resolve('./src/views/client/index.js')
    ]
  }

output配置

output: {
  filename: '[name].[hash:8].js',  // 因爲是多應用,所以必須通過名稱匹配的方式生成打包文件
  path: './dist',
  publicPath: '/'
}

html配置

因爲是多頁面應用,所以每個應用都有一個獨立的html文件

通過html-webpack-plugin插件來配置,需要達到以下目標:

  • 每個html文件只加載對應應用需要的依賴包
  • 可以根據不同環境加載不一樣的依賴包

開發環境(dev):

plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: resolve('./src/views/admin/index.html'),
      chunks: ['admin'], // 設置chunks可以只安裝指定的依賴包,如果不設置,則會將所有依賴包全部加載
      inject: true
    }),
    new HtmlWebpackPlugin({
      filename: 'client.html',
      template: resolve('./src/views/client/index.html'),
      chunks: ['client'], // 設置chunks可以只安裝指定的依賴包,如果不設置,則會將所有依賴包全部加載
      inject: true
    })
  ]

生產環境(prod):

plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: resolve('./src/views/admin/index.html'),
      chunks: ['admin'],
      inject: true,
      minify: true  // 壓縮文件
    }),
    new HtmlWebpackPlugin({
      filename: 'client.html',
      template: resolve('./src/views/client/index.html'),
      chunks: ['client'],
      inject: true,
      minify: true // 壓縮文件
    })
  ]

如果在設置了公共包或者配置了optimization: {runtimeChunk: 'single'}
這時,在chunks中一定要加入這些依賴包
如:chunks: ['runtime', 'common', 'amdin']

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