已配置webpack.config.js但html-loader仍无法正常工作的问题
Webpack使用html-loader仍报错的解决方案
问题场景
使用require("./about.html")导入HTML文件时,触发如下错误:
Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
已安装html-loader并配置了webpack.config.js,配置代码如下,但错误未解决:
module.exports = { module: { rules: [ { test: /\.html$/i, loader: "html-loader", options: { minimize: true, } }, ], }, };
排查与解决步骤
- 校验版本兼容性:
Webpack 5需搭配html-loaderv4及以上版本,Webpack 4则对应v3及以下版本。版本不匹配会导致加载失败,可卸载现有包后重装对应版本,示例命令(Webpack 5环境):npm uninstall html-loader && npm install html-loader@latest - 确认配置文件加载:
确保Webpack运行时读取了正确的配置文件,若配置文件不是默认的webpack.config.js,需通过--config参数指定路径,比如:webpack --config ./custom-webpack.config.js - 检查规则匹配有效性:
确认test: /\.html$/i能正确匹配目标HTML文件的路径,同时排查是否有其他Loader规则覆盖了该配置。 - 清理缓存后重建:
清理Webpack缓存后重新执行构建,避免缓存导致的配置不生效:rm -rf node_modules/.cache && webpack
内容的提问来源于stack exchange,提问作者U_A
相关产品推荐
相关产品推荐

