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




  
  Contact


  

Contact page

image

image

有个问题,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')

结果:

image

image

这样就 OK 了。

先说这么多。

你可能感兴趣的:(10.配置多个 HTML 文件)