React.js npm模块Fork后本地开发如何实现代码实时生效?
Hey there! I’ve been stuck with this exact frustration before—having to run a build every single time I tweak my linked React package is such a buzzkill. Let’s break down the solutions that’ll let you see changes instantly:
1. Point package.json to Your Source Code (and Configure the Host Project to Compile It)
Most React packages have their main field in package.json pointing to compiled output (like dist/index.js). To skip manual builds entirely, redirect this entry to your raw source files:
- Open your linked package’s
package.json - Change the
mainvalue from something like"dist/index.js"to"src/index.js"(adjust the path to match your actual entry file)
But a heads-up: if your host project uses Create React App (CRA), it won’t compile files in node_modules by default—including your linked package. Fix this with these steps:
For CRA Projects (Without Ejecting)
Use react-app-rewired and customize-cra to tell Webpack to process your linked package:
- Install dependencies in your host project:
npm install --save-dev react-app-rewired customize-cra - Create a
config-overrides.jsfile in your host project root:const { override, babelInclude } = require('customize-cra'); const path = require('path'); module.exports = override( babelInclude([ path.resolve('src'), // Keep the default src directory path.resolve('../path-to-your-linked-package'), // Add your package's local path ]) ); - Update your host project’s
package.jsonscripts to usereact-app-rewired:"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test" }
Now when you start your host project, it’ll compile your linked package’s source files directly—changes will show up instantly after saving.
2. Enable Watch Mode in Your Linked Package
If you prefer keeping compiled output (maybe your package uses Rollup/Webpack for bundling), set up a watch script to auto-rebuild whenever you edit source files:
Example for Rollup
Add a watch script to your linked package’s package.json:
"scripts": { "build": "rollup -c", "watch": "rollup -c --watch" }
Run yarn watch in your package’s terminal—every save triggers an auto-rebuild, and your host project will pick up the updated dist files right away (refresh the browser if hot-reload doesn’t kick in automatically).
Example for Webpack
Add a watch script for Webpack:
"scripts": { "build": "webpack --mode production", "watch": "webpack --mode development --watch" }
Example for Babel (Simple Projects)
If you’re using Babel without a bundler:
"scripts": { "build": "babel src --out-dir dist", "watch": "babel src --out-dir dist --watch" }
3. Bonus: Fix Browser Caching Glitches
Sometimes browsers hold onto old files even after setup. Fix this quickly:
- Open browser DevTools (F12)
- Go to the Network tab
- Check the Disable cache box (keep DevTools open for this to work)
内容的提问来源于stack exchange,提问作者Jonathan

