webpack进阶--02--多页面应用配置

本文介绍了一种基于Webpack的多应用项目配置方案,包括开发和生产环境下的entry配置、output配置及html配置,并实现了根据不同环境加载对应的依赖包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目文件结构:

├─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']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值