当前位置:  首页>> 技术小册>> Webpack零基础入门

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

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

webpack.config.js

  1. ...
  2. new HtmlWebpackPlugin({
  3. template: './src/index.html',
  4. filename: 'index.html',
  5. minify: {
  6. collapseWhitespace: true,
  7. },
  8. hash: true,
  9. })
  10. ...

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

webpack.config.js

  1. new HtmlWebpackPlugin({
  2. template: './src/index.html',
  3. filename: 'index.html',
  4. minify: {
  5. collapseWhitespace: true,
  6. },
  7. hash: true,
  8. }),
  9. new HtmlWebpackPlugin({
  10. template: './src/contact.html',
  11. filename: 'contact.html',
  12. minify: {
  13. collapseWhitespace: true,
  14. },
  15. hash: true,
  16. })

src/contact.html

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>Contact</title>
  5. </head>
  6. <body>
  7. <p>Contact page</p>
  8. </body>
  9. </html>



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

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

那我们来改造一下:

  1. ...
  2. module.exports = {
  3. entry: {
  4. "app.bundle": './src/app.js',
  5. // 这行是新增的。
  6. "contact": './src/contact.js'
  7. },
  8. ...
  9. plugins: [
  10. new CleanWebpackPlugin(pathsToClean),
  11. new HtmlWebpackPlugin({
  12. template: './src/index.html',
  13. filename: 'index.html',
  14. minify: {
  15. collapseWhitespace: true,
  16. },
  17. hash: true,
  18. // 这行是新增的。
  19. excludeChunks: ['contact']
  20. }),
  21. new HtmlWebpackPlugin({
  22. template: './src/contact.html',
  23. filename: 'contact.html',
  24. minify: {
  25. collapseWhitespace: true,
  26. },
  27. hash: true,
  28. // 这行是新增的。
  29. chunks: ['contact']
  30. }),
  31. new ExtractTextPlugin('style.css')
  32. ],
  33. ...
  34. };

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

src/contact.js

  1. console.log('hi from contact js')

结果:



该分类下的相关小册推荐: