Webpack 5多入口配置报错:Chrome扩展React项目问题排查
Webpack多入口配置报错解决
问题详情
搭建Chrome扩展的React项目时,用Webpack 5配置多入口后,执行npm run build抛出以下错误:
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.entry[0] should be a non-empty string.
-> A module that is loaded upon startup. Only the last one is exported.
当前webpack.config.js的多入口配置如下(单字符串入口时build正常):
const path = require("path"); module.exports = { mode: "development", entry: { editor: './src/editor/editor.js', action: './src/action/action.js' }, output: { filename: '[name]/[name].js', path: path.resolve(__dirname, "build"), }, target: "web", devServer: { port: "3000", static: ["./build"], open: true, hot: true, liveReload: true, }, resolve: { extensions: [".js", ".jsx", ".json", ".ts"], }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: "babel-loader", }, ], }, };
package.json核心配置:
{ "name": "task_mananger_ext", "version": "1.0.0", "main": "./src/editor/editor.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server .", "build": "webpack ." }, "devDependencies": { "@babel/core": "^7.26.0", "@babel/eslint-parser": "^7.25.9", "@babel/plugin-transform-runtime": "^7.25.9", "@babel/preset-env": "^7.26.0", "@babel/preset-react": "^7.25.9", "@babel/runtime": "^7.26.0", "babel-eslint": "^10.1.0", "babel-loader": "^9.2.1", "webpack": "^5.96.1", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.1.0" }, "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }
问题根源
你在package.json的scripts里给webpack命令加了.参数,这个参数会被webpack当作入口文件路径解析,直接覆盖了webpack.config.js中配置的多入口对象。
当执行webpack .时,webpack会把当前目录作为入口,和你配置的多入口合并成数组格式,而Webpack的多入口要求是对象结构,因此触发了schema校验错误。
修复方案
修改package.json中的scripts,去掉webpack命令后面的.参数:
{ "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server", "build": "webpack" } }
修改后,webpack会自动读取项目根目录的webpack.config.js配置,使用你定义的多入口对象,不会再出现参数冲突的问题。
补充说明
如果后续需要指定非默认路径的配置文件,可使用--config参数,例如:
webpack --config ./config/custom-webpack.js
内容的提问来源于stack exchange,提问作者ojete_sucio
相关产品推荐
相关产品推荐

