I have the following basic react structure
Project
|
--- src
|
--- App
|
--- file-tree-1
|
--- file-tree-2
If I run npm run start and npm run build then all the files within App are targeted, which is the correct behaviour.
However, I'd like to do something like the following pseudo code:
// The following would build and would only includes the files and folders under file-tree-1:
npm run start --use file-tree-1
npm run build --use file-tree-1
// The following would do the same, but targeting file-tree-2 files and folders only
npm run start --use file-tree-2
npm run start --use file-tree-2
I know the code above is not possible the way it is written. But can I achieve what is done there? I basically need to use the same code base for two separate outputs, but not sure how to do it. How can I customize the build files.
Thank you.
-
If you are using CRA ('react-scripts'), it just uses webpack. Webpack supports multiple entry points (which is what you're after). There are npm packages that let you change the webpack config without ejecting the CRA (react-app-rewired is one), but since CRA is not getting updates anymore you could probably just eject the app and get direct access to the config that way. This older question can probably give you an idea on how to go about it.Jacob Smit– Jacob Smit2025年04月10日 21:53:48 +00:00Commented Apr 10, 2025 at 21:53
-
@JacobSmit - Thank you for your advice. I will follow the links you provided.Greeso– Greeso2025年04月11日 13:55:44 +00:00Commented Apr 11, 2025 at 13:55
1 Answer 1
I am answering my own question so others who have the same problem can benefit from it.
After much struggle, I think I came up with a solution that would not need any additional package installed, and without running npm run eject (which was important to me). I did the following:
In
package.json, I modifiedscriptsas follows (by adding the last three entries):"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "build-tree-1": "BUILD_PATH='./tree1' REACT_APP_TREE1='tree1' react-scripts build", "build-tree-2": "BUILD_PATH='./tree2' REACT_APP_TREE2='tree2' react-scripts build", "build-trees": "npm run build-tree-1 && npm run build-tree-2" }In my code, I added conditional variables, as follows (please note this is the pseudo code):
Project | --- src | --- App | --- {(process.env.REACT_APP_TREE1 === 'tree1') && code for: file-tree-1 } | --- {(process.env.REACT_APP_TREE2 === 'tree2') && code for: file-tree-2 }To run a build, I type
npm run build-tree-1ornpm run build-tree-2, which will build those files into their respective folders. I can also run both builds at once vianpm run build-trees
PS: This is the general idea, hope it helps.