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 了。

先说这么多。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Webpack学习总结 此文只是自己学习webpack的一些总结,方便自己查阅,阅读不变,非常抱歉!! 下载安装:...
    Lxs_597阅读 1,149评论 0赞 0
  • jHipster - 微服务搭建 CC_简书[https://www.jianshu.com/u/be0d56c4...
    quanjj阅读 993评论 0赞 2
  • 记得2004年的时候,互联网开发就是做网页,那时也没有前端和后端的区分,有时一个网站就是一些纯静态的html,通过...
    阳阳阳一堆阳阅读 3,518评论 0赞 5
  • 文/流浪带着上帝 原创作品,版权所有,禁止转载 遇见亮是在高一开学的第一课。上课铃声响后,我看见迟到的亮正从讲桌前...
    一言boss阅读 418评论 0赞 0
  • 1【今日分享】如何用精油调理家人的感冒的 1.感冒预防 预防是最有必要做的事,虽然麻烦,但比起生病时的护理,心情一...
    粉面小猪阅读 2,028评论 0赞 2

友情链接更多精彩内容