(03)webpack 配置处理html文件

it2024-05-10  45

webpack处理html文件需要使用html-webpack-plugin插件

webpack使用插件一般有三个步骤 1安装 2引入 3使用

1 安装

2 引入和使用 引入使用require 语法 .

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

使用 HtmlWebpackPlugin 是一个构造函数,new一个实例对象即可

new HtmlWebpackPlugin() const { resolve } = require('path'); /** 引入插件 */ const HtmlWebpackPlugin = require(require.resolve('html-webpack-plugin')); module.exports = { /** 输入 */ entry: './src/index.js', /** 输出 */ output: { filename: 'bundle.js', path: resolve(__dirname, 'bundle'), }, /** loader 配置 1下载 2使用(配置loader) */ module: { rules: [ { /** 对所有以.css结尾的文件进行匹配 */ test: /\.css$/, /** use执行顺序, 从右往左,从下往上 */ use: [ /** 创建一个style标签, 将js中的css样式资源插入进去,添加到页面生效 */ // 'style-loader', /** 将css文件编程commonjs模块加载js中,里面内容是样式字符串 */ // 'css-loader', { loader: 'style-loader' }, { loader: 'css-loader', }, ], }, { /** 对所有以.css结尾的文件进行匹配 */ test: /\.less$/, use: ['style-loader', 'css-loader', 'less-loader'], }, { test: /\.scss/, //配置sass转css use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, ], }, ], }, /** 插件配置 1下载 2引入 3使用 */ plugins: [ /** 可以多次使用,生成多个html文件 */ new HtmlWebpackPlugin(), /** 插件实现的功能 默认会创建一个空的html,自动引入打包输出的所有资源 */ new HtmlWebpackPlugin({ /** 将路径的html复制一份,自动引入打包输出的所有资源 */ template: './src/index.html', // alwaysWriteToDisk: true, /** 创建的html的名字,如果不设置默认为index.html */ filename: 'text.html', title: 'dx', }), ], /** 模式开发模式 development 或者生产模式 production */ mode: 'development', };

除了代码中展示的基础配置以外,html-webpack-plugin还有许多好玩的配置项,大家可以在官网的github中找到

附赠html-webpack-plugin插件的配置链接 :https://github.com/jantimon/html-webpack-plugin#configuration

ps: 我在使用的过程中遇到一个html-webpack-plugin的bug,template配置了html文件后,打包生成的html报错

ERROR in TypeError: The 'compilation' argument must be an instance of Compilation 产生的原因是 项目所在的环境有多个node_modules,项目的父级目录也存在一个node_modules文件夹

解决的办法 删除多余的node_modules,根据依赖重新安装一次即可 重新下包前,请删除调packge-lock或者yarn-lock文件哦!!

npm i

关于上述的问题,有的同学怀疑和版本号有关系,展示一下我的版本号,我是用的cnpm下载的包,多次尝试都没有问题。

{ "name": "webpack", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "css-loader": "^5.0.0", "html-webpack-plugin": "^4.5.0", "less": "^3.12.2", "less-loader": "^7.0.2", "style-loader": "^2.0.0", "webpack": "^5.2.0", "webpack-cli": "^4.1.0" } }
最新回复(0)