You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Webpack入口配置失效:如何将入口改为./src/index.js?

问题:Webpack入口文件修改无效

我正在使用无CRA的React项目,希望将Webpack的入口文件从根目录的./index.js改为./src/index.js。尝试了多种entry配置方式,但均无效,Webpack仍默认使用根目录的index.js。

当前package.json配置

{
  "scripts": {
    "build": "Webpack ."
  },
  "devDependencies": {
    "@babel/cli": "^7.18.10",
    "@babel/core": "^7.19.1",
    "@babel/eslint-parser": "^7.19.1",
    "@babel/plugin-transform-runtime": "^7.19.1",
    "@babel/preset-env": "^7.19.1",
    "@babel/preset-react": "^7.18.6",
    "@babel/runtime": "^7.19.0",
    "babel-loader": "^8.2.5",
    "eslint": "^8.23.1",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-jest": "^27.0.4",
    "path": "^0.12.7",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.11.1"
  },
  "dependencies": {
    "path": "^0.12.7",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "@babel/cli": "^7.17.0"
  }
}

当前webpack.config.js配置

module.exports={
    mode: "development", 
    entry: "./index.js", 
    output: {
        path: path.resolve(__dirname, "public"),
        filename: "main.js"
    },
    target: "web",
    resolve: {
        extensions: ['.js','.jsx','.json'] 
    },
    module:{
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use:  'babel-loader'
            }
        ]
    }
}

尝试过的entry配置

  • entry: path.resolve(__dirname, "src/index"),
  • entry: "src/index",
  • entry: path.resolve(__dirname, "src/index.js"),
  • entry: "src/index.js"

解决方案

1. 修复package.json中的build命令

你的build脚本里写了Webpack .,这里的.是直接指定Webpack使用当前目录的index.js作为入口,会完全覆盖webpack.config.js里的entry配置。需要把这个.去掉,同时修正命令首字母大小写:

"scripts": {
  "build": "webpack"
}

2. 完善webpack.config.js配置

  • 首先在配置文件顶部引入path模块(当前配置缺失,会导致path.resolve报错):
const path = require('path');
  • 然后修改entry为目标路径:
entry: path.resolve(__dirname, "src/index.js"),

或者直接使用相对路径:

entry: "./src/index.js",

3. 验证修改

确保src/index.js文件存在,运行npm run build后,Webpack将正确使用src/index.js作为入口文件打包。


内容的提问来源于stack exchange,提问作者vamsi penta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:00:17