I'm a newbie here with web-development and recently started pushing my simple web-app to a GitHub page. I quickly discovered that my page won't render after I integrated react-router
with it because my dev and prod URL links are different.
My question is, how can I set up my package.json
and .env
such that it will correctly render my URLs?
My .env
file looks like this:
REACT_APP_PUBLIC_URL="my-site"
and my package.json
looks like:
"scripts": {
"start": "NODE_ENV=development react-scripts start",
"start:prod": "NODE_ENV=production react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
Inside my Index.js
, I'm doing this:
if (process.env.NODE_ENV === "production") {
require("dotenv").load();
}
console.log("PROCESS.ENV.NODE_ENV: ", process.env.NODE_ENV); // This prints "development"
console.log("PROCESS.ENV.PUBLIC_URL: ", process.env.REACT_APP_PUBLIC_URL); // This prints "my-site"
When I run npm run start:prod
, I would think that it sets the NODE_ENV
to production
but it doesn't seem to be doing that.
Basically, what I want to do is during development, my process.env.PUBLIC_URL
should be ""
and during production, it should be "my-site"
. That way, my router can correctly render the corresponding views. Thanks for your help!
React-scripts sets NODE_ENV automatically, see article in medium.com. One of the options is using different env variables, case MY_APP_ENV
It's possible that react-scripts
is just overriding it to be development
. Here is some source I dug up :O
https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/scripts/start.js#L11
Perhaps options you can consider is use a different env variable (you can define whatever you want quite honestly. Or you can just leave the production
build to react-scripts
/ create-react-app
since it seems like they have some internal logic to do this for you .
创建.env.qa1
并添加构建脚本:
"build-qa1": "sh -ac '. .env.qa1; react-scripts start'"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.