欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webpack 打包多html

程序员文章站 2022-03-03 23:36:13
...

webpack 打包多html

安装 node.js

安装 node.js https://nodejs.org/ (管理员身份)

安装 webpack

npm init -y

npm install webpack webpack-cli webpack-dev-server -D

  • 运行 webpack -v 报错,则以管理员身份运行 webstorm 或 vscode ,终端运行 set-ExecutionPolicy RemoteSigned ,以后可以不需管理员身份打开项目了。

安装 html-webpack-plugin 插件

npm install html-webpack-plugin -D

创建多个 html 文件

  • src/index.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Index - Title</title>
    6. </head>
    7. <body>
    8. <p>Index page</p>
    9. </body>
    10. </html>
  • src/list.html

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>List - Title</title>
    6. </head>
    7. <body>
    8. <p>List page</p>
    9. </body>
    10. </html>
  • 其它 src/js/ 目录下文件

    1. // global.js
    2. module.exports = {
    3. duble: (a) => a * 2,
    4. }
    1. // index.js
    2. let {duble} = require('./global');
    3. let one = require('./one');
    4. console.log('1 * 2 = ' + duble(one.a));
    1. // one.js
    2. module.exports = {
    3. a: 1,
    4. }
    1. // two.js
    2. module.exports = {
    3. b: 2,
    4. }

创建 webpack 配置

  • webpack.config.js

    1. const {resolve} = require("path");
    2. const htmlWebpackPlugin = require("html-webpack-plugin");
    3. module.exports = {
    4. entry: {
    5. main: ["./src/js/index.js"],
    6. list: ["./src/js/one.js", "./src/js/two.js"]
    7. },
    8. output: {
    9. path: resolve(__dirname, "dist"),
    10. filename: "[name].js"
    11. },
    12. module: {
    13. },
    14. plugins: [
    15. new htmlWebpackPlugin({
    16. template: "./src/index.html",
    17. filename: "index.html",
    18. chunks: ["main"],
    19. minify: {
    20. collapseWhitespace: true,
    21. removeComments: true,
    22. }
    23. }),
    24. new htmlWebpackPlugin({
    25. template: "./src/list.html",
    26. filename: "list.html",
    27. chunks: ["list"],
    28. minify: {
    29. collapseWhitespace: true,
    30. removeComments: true,
    31. }
    32. })
    33. ],
    34. // mode: "development",
    35. mode: "production"
    36. }
  • 终端运行 webpack 生成 dist 下四个打包文件

webpack 打包多html