webpack-demo002,使用html-webpack-plugin

使用html-webpack-plugin

  • 在demo001的基础上增加 html-webpack-plugin
  • 安装html-webpack-plugin
  • 新增src目录内容
  • 修改webpack配置文件
  • 修改运行脚本
  • 运行

在demo001的基础上增加 html-webpack-plugin

https://blog.csdn.net/qq_26264237/article/details/131280125

安装html-webpack-plugin

npm i -D html-webpack-plugin

新增src目录内容

修改/src/index.html
主要去掉脚本引入部分,由html-webpack-plugin完成脚本引入

<script src="../dist/main.js"></script>
DOCTYPE html>
DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testtitle>
head>

<body>

body>

html>

修改webpack配置文件

新增插件方面配置

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // 入口文件 默认值是 ./src/index.js
    entry: "./src/index.js",
    // 打包后的出口文件 默认值是 ./dist/main.js
    output: {
        // 输出的文件名称
        filename: 'main.js',
    },
    // 使用开发模式打包 development, production 或 none
    mode: "development",
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './src/index.html',
            // inject:是否在template文件中插入打包的js文件
            inject: true,
            title: 'webpack is good',
            chunks: ['main']
        })
    ]
}

修改运行脚本

package.json文件变化,多出了html-webpack-plugin依赖

{
  "name": "webpack-demo002-html-webpack-plugin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^5.5.3",
    "webpack": "^5.87.0",
    "webpack-cli": "^5.1.4"
  }
}

运行

执行命令进行打包,生成/dist/main.js文件
npm run dev

右键 /src/index.html open with live server(需要安装插件)
http://127.0.0.1:5501/src/index.html

你可能感兴趣的:(webpack,html,javascript)