webpack 3 零基础入门教程 #10 - 配置多个 HTML 文件

之前我们只写了一个 html 文件,就是 src/index.html,但是有时候我们是需要多个的,这个时候,怎么办呢?

之前我们是这么做的,用了 html-webpack-plugin 这个插件来输出 html 文件。

webpack.config.js

...
new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  minify: {
    collapseWhitespace: true,
  },
  hash: true,
})
...
复制代码

之前怎么做,现在还是怎么做,我们复制一下,改个名字不就好吗?

webpack.config.js

new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  minify: {
    collapseWhitespace: true,
  },
  hash: true,
}),
new HtmlWebpackPlugin({
  template: './src/contact.html',
  filename: 'contact.html',
  minify: {
    collapseWhitespace: true,
  },
  hash: true,
})
复制代码

src/contact.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Contact</title>
</head>
<body>
  <p>Contact page</p>
</body>
</html>
复制代码

有个问题,contact.html 使用的 js 和 css 跟 index.html 是一模一样的

如果我要让 contact.html 使用跟 index.html 不同的 js,如何做呢?(只要保证 js 不同,css 也会不同的,因为 css 也是由 js 里 import 的嘛)

那我们来改造一下:

...

module.exports = {
  entry: {
    "app.bundle": './src/app.js',
    // 这行是新增的。
    "contact": './src/contact.js'
  },
  ...
  plugins: [
    new CleanWebpackPlugin(pathsToClean),
    new HtmlWebpackPlugin({
      template: './src/index.html',
      filename: 'index.html',
      minify: {
        collapseWhitespace: true,
      },
      hash: true,
      // 这行是新增的。
      excludeChunks: ['contact']
    }),
    new HtmlWebpackPlugin({
      template: './src/contact.html',
      filename: 'contact.html',
      minify: {
        collapseWhitespace: true,
      },
      hash: true,
      // 这行是新增的。
      chunks: ['contact']
    }),
    new ExtractTextPlugin('style.css')
  ],
  ...
};
复制代码

上面的 excludeChunks 指的是不包含, chunks 代表的是包含。

src/contact.js

console.log('hi from contact js')
复制代码

结果:

这样就 OK 了。

先说这么多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值