webpack之多页面应用打包

多页面应用(MPA)概念

每⼀次⻚⾯跳转的时候,后台服务器都会给返回⼀个新的 html ⽂档,这种类型的⽹站就是多⻚⽹站,也叫做多⻚应⽤。

多页面打包思路

  1. 每个页面对应一个entry,一个html-webpack-plugin
  2. 需要解决避免每次新增或删除页面都要修改webpack配置
  3. 使用glob模块,用它可以查找符合特定规则的文件路径名

webpack中写入这段核心代码能够实现自动化添加或删除页面的功能,但是需要文件目录需要保持一定规律。如:

{
index: ‘d:/code/webpack/my-project/chapter2/src/index/index.js’,
search: ‘d:/code/webpack/my-project/chapter2/src/search/index.js’
}

入口都是在src/*/index.js

const setMPA = () => {
  const entry = {}
  const htmlWebpackPlugins = []
  const entryPaths = glob.sync(path.join(__dirname, './src/*/index.js'))
  Object.keys(entryPaths).forEach(index => {
    const entryPath = entryPaths[index]
    const match = entryPath.match(/src\/(.*)\/index\.js/)
    const pageName = match && match[1]
    
    entry[pageName] = entryPath
    htmlWebpackPlugins.push(
      new HtmlWebpackPlugin({
        template: path.join(__dirname, `src/${pageName}/index.html`),
        filename: `${pageName}.html`,
        chunks: [pageName],
        inject: true,
        minify: {
          html5: true,
          collapseWhitespace: true,
          preserveLineBreaks: false,
          minifyCSS: true,
          minifyJS: true,
          removeComments: false
        }
      })
    )
  })
  return { entry, htmlWebpackPlugins }
}

const { entry, htmlWebpackPlugins } = setMPA();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值