5分钟掌握 webpack 多页应用配置

本文详细介绍如何使用Webpack配置多页应用,通过多入口和html-webpack-plugin生成多个HTML文件,利用glob遍历文件自动化配置,以及提取公共JS和HTML片段优化打包结果。

基本思路

webpack 多页应用配置的基本思路是采用多入口配置,然后多次调用 html-webpack-plugin 来生成 html 文件。

假设项目的目录结构为:

src
 |-pages
     |-home
         |-home.html
         |-home.js
     |-about
         |-about.html
         |-about.js
复制代码

webpack.config.js:

const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    home: 'src/pages/home/home.js',
    about: 'src/pages/about/about.js',
  },
  output: {
    filename: 'js/[name].[chunkhash:8].js',
    path: __dirname + '/dist'
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: 'src/pages/home/home.html',
      filename: 'home.html',
      chunks: ['home'] // 默认会将打包出的所有 js 插入 html。故需指明页面需要的模块
    }),
    new HTMLWebpackPlugin({
      template: 'src/pages/about/about.html',
      filename: 'about.html',
      chunks: ['about']
    })
  ]
}
复制代码

运行 webpack,最终将生成:

dist
 |-js
   |-home.js
   |-about.js
 |-home.html
 |-about.html
复制代码

可以发现,每个 html 中已经以 script 标签的形式插入了对应的 js 文件。

使用 glob 遍历文件

由于每增加一个页面,都需要手动的添加 entry 和 plugin,显得很费事儿。因此我们引入 glob 来遍历读取 html 文件,然后动态配置 entry 与 plugin。当然,需要事先 npm install glob

const glob = require('glob')
glob.sync('src/pages/**/*.html')
// 返回符合 pattern 参数的文件路径数组
// ['src/pages/about/about.html', 'src/pages/home/home.html']
复制代码

于是 entry 和 plugin 都可以自动生成:

const HTMLReg = //([w-]+)(?=.html)/
const JSReg = //([w-]+)(?=.js)/

const html = glob.sync('src/pages/**/*.html').map(path => {
  let name = path.match(HTMLReg)[1] // 从路径中提取出文件名
  return new HTMLWebpackPlugin({
    template: path,
    filename: name + '.html',
    chunks: [name]
  })
})

const entries = glob.sync('src/pages/**/*.js').reduce((prev, next) => {
  let name = next.match(JSReg)[1]
  prev[name] = './' + next
  return prev
}, {})

module.exports = {
  entry: entries,
  output: {
    filename: 'js/[name].[chunkhash:8].js',
    path: __dirname + '/dist'
  },
  plugins: html
}
复制代码

提取公共 js

提取公共 js 使用 CommonsChunkPlugin 即可

const html = glob.sync('src/pages/**/*.html').map(path => {
  let name = path.match(HTMLReg)[1] // 从路径中提取出文件名
  return new HTMLWebpackPlugin({
    template: path,
    filename: name + '.html',
    chunks: [name, 'vendor'] // 加上公共模块
  })
})
// ...
plugins: [
  new webpack.optimize.CommonsChunkPlugin({
     name: 'vendor'
  })
].concat(html)
复制代码

提取公共的 html 片段

HTMLWebpackPlugin 本身就支持使用 ejs 的语法来插入 html 片段。我们新增加一个 公共模板的目录:

src
 |-pages
 |-template
      |-header.html
复制代码

header.html 大概长这样:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="dns-prefetch" href="//css.alikunlun.com">
<link rel="dns-prefetch" href="//js.alikunlun.com">
<link rel="dns-prefetch" href="//img.alikunlun.com">
<meta name="keywords" content="keywords">
<meta name="description" content="description">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="applicable-device" content="mobile">
<meta name="format-detection" content="telephone=no">
<meta http-equiv="Cache-Control" content="no-cache">
复制代码

在 home.html 中引入 header.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <%= require('html-loader!../../template/header.html') %>
  <title>home</title>
</head>
复制代码

webpack 中除了 js 以外的资源都需要相应 loader 处理,require('html-loader!../../template/header.html') 表示采用 html-loader 处理 header.html(需事先 npm install html-loader)

注意不需要在 webpack.config.js 的 module 中配置 html-loader,否则将引入失败。

图片资源也可以采用上述方式引入,并且不需要指明 loader:

<img src="<%= require('./name.png') %>">复制代码

来源:https://www.imooc.com/article/23643#


转载于:https://juejin.im/post/5bebf00bf265da61616e4065

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值