React项目中webpack.config.js放置位置及Worker Loader配置疑问
Hey there! Since your project uses react-scripts start to launch, it's a Create React App (CRA) project—and CRA intentionally hides the underlying webpack and Babel config files by default to keep things simple. That's why you don't see a webpack.config.js or .babelrc in your project root. Here's how you can add the worker-loader configuration safely:
Option 1: Eject (Irreversible, Not Recommended for Beginners)
CRA lets you "eject" to expose all the config files, but this is a one-way operation—you can't go back to the simplified CRA setup after doing this:
- Run
npm run ejectoryarn ejectin your terminal. This will generate aconfigfolder in your project root, containingwebpack.config.js(and separate configs for production/development environments). - You can then edit the relevant
webpack.config.jsfile to add your worker-loader rules directly.
Option 2: Use react-app-rewired + customize-cra (Recommended, No Eject Needed)
This approach lets you override CRA's default webpack config without ejecting, which is safer for maintaining your project long-term:
- Install the required dependencies:
npm install --save-dev react-app-rewired customize-cra worker-loader - Create a
config-overrides.jsfile in your project root (this is where you'll define your custom webpack rules, instead of creating a standalonewebpack.config.js):const { override, addWebpackModuleRule } = require('customize-cra'); module.exports = override( // Add worker-loader rule addWebpackModuleRule({ test: /\.worker\.js$/, // Match files ending with .worker.js use: { loader: 'worker-loader' } }) ); - Update your
package.jsonscripts to usereact-app-rewiredinstead ofreact-scripts:"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }
Why You Can't Find webpack.config.js
Under the hood, CRA stores its default webpack config in the node_modules/react-scripts/config folder. You could technically edit files there, but this is not recommended—any updates to react-scripts would overwrite your changes, and it makes your project harder to maintain.
Since you're new to React, sticking with the react-app-rewired method is the best bet—it keeps your project structure clean and avoids the permanent changes from ejecting.
内容的提问来源于stack exchange,提问作者Tomáš Zato

