添加MiniCssExtractPlugin后Chrome扩展popup.js无法访问求助
Chrome扩展使用MiniCssExtractPlugin后popup.js无法访问(ERR_FILE_NOT_FOUND)
问题描述
在开发Chrome扩展项目时,通过MiniCssExtractPlugin向content脚本注入CSS的功能正常,但popup.js突然无法访问,报错:
Your file couldn’t be accessed. It may have been moved, edited, or deleted. ERR_FILE_NOT_FOUND
仅新增了以下配置:
craco.config.js 新增代码
webpack: { configure: (webpackConfig, {env, paths}) => { return { ... plugins: [new MiniCssExtractPlugin({ filename: "[name].css" })], // 新增的插件配置 ... } } }
manifest.json 新增代码
"content_scripts": [ { "matches": ["<all_urls>"], "css": ["./main.css"], // 新增的CSS引用 ... } ]
使用的mini-css-extract-plugin版本为^2.6.1。
解决方案
避免直接覆盖webpack plugins数组
你当前的写法直接返回了一个新的plugins数组,这会替换掉Create React App默认的所有webpack插件(包括处理popup.js入口的插件),导致popup相关资源未被正确打包。正确的做法是在原有plugins数组基础上添加新插件,同时替换CSS规则中的style-loader:// 修正后的craco.config.js const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { webpack: { configure: (webpackConfig, {env, paths}) => { // 替换CSS规则中的style-loader为MiniCssExtractPlugin.loader const cssRuleIndex = webpackConfig.module.rules.findIndex(rule => rule.oneOf); if (cssRuleIndex !== -1) { webpackConfig.module.rules[cssRuleIndex].oneOf.forEach(rule => { if (rule.test && rule.test.test('.css')) { rule.use = rule.use.map(loader => { if (loader.loader === require.resolve('style-loader')) { return { loader: MiniCssExtractPlugin.loader }; } return loader; }); } }); } // 在原有plugins数组末尾添加插件,而非替换 webpackConfig.plugins.push(new MiniCssExtractPlugin({ filename: "[name].css" })); return webpackConfig; } } };核对资源路径与manifest配置
- 检查打包后的输出目录(通常是
build文件夹),确认main.css和popup.js都存在,且路径与manifest及popup.html中的引用一致。 - 确保popup的manifest配置正确,例如:
"action": { "default_popup": "popup.html" } - 检查popup.html中引用popup.js的路径是否匹配打包后的实际路径,比如:
<script src="./static/js/popup.js"></script>
- 检查打包后的输出目录(通常是
清理缓存后重新打包
执行npm run build前,先删除build文件夹或使用npm run build --clean清除旧缓存,避免缓存导致的路径异常。
内容的提问来源于stack exchange,提问作者Mingyu Jeon
相关产品推荐
相关产品推荐

