You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<!DOCTYPE html><htmllang="en"><head><title>React App</title><scripttype="text/javascript">window.RUNTIME={SERVICE: "http://xyz.api"};</script></head><body><noscript>You need to enable JavaScript to run this app.</noscript><divid="root"></div></body></html>
importDebugfrom'debug';constdebug=Debug('app:config');classConfig{constructor(){debug(`NODE_ENV: ${process.env.NODE_ENV}`);if(window.RUNTIME&&window.RUNTIME.SERVICE){this.service=window.RUNTIME.SERVICE;}else{if(process.env.REACT_APP_SERVICE){this.service=process.env.REACT_APP_SERVICE;}else{thrownewError("Missing service configration");}}}}exportdefaultnewConfig();
Node
这个和传统Java, C#应用程序基本一致,
index.js
config是用来做常规设置,而dotenv区别config主要有2个因素:
注:
对应的webpack.config.js
在运行build的时候还是需要先制定NODE_ENV
NODE_ENV=production node bundle.js
再来看dotenv-cli, 这样可以去掉require('dotenv').config(),然后在运行时选择NODE_ENV,
.env
.env.production
ok, 然后配置运行指令,
这样就比较有一致性了。
最后补充一下pm2的情况,pm2的环境变量建议还是直接在ecosystem.config.js中设置,不要混dotenv。
最终可以整理如下:
参考:
React
React的配置比Node会受限一些,主要是因为它运行在浏览器中,刚刚的config都是运行时,但React的配置则基本是编译时,因为.env的内容直接hard code到最终编译的js, 所以和Node是不同的,遵循create-react-app的要求,可以采用.env和.env.production等支持多环境,在加载.env.production时会先加载.env。
如果需要运行时,就比如build以后需要做配置,则需要在HTML中引入js,
然后在页面获取,
此外,yarn start时NODE_ENV=development, yarn build后则NODE_ENV=production
现在需求来了,
config.js
在index.js中直接可以
import './config'
, 然后在app.js就可以消费了,最后补充一下env,
.env
REACT_APP_SERVICE=http://localhost:9007
.env
REACT_APP_SERVICE=https://api.space365.live
如果在HTML设置了service,则无视.env
上述代码可以在这里获取。
The text was updated successfully, but these errors were encountered: