使用环境变量设置基本href [英] Setting base href using Environment variables
问题描述
需要根据构建环境配置为< base href = />
标记设置href值。
Need to set the href value for <base href=""/>
tag based on build environment configuration.
例如:
登台应具有< base href = / staging />
产品应具有< base href = / />
当前设置:
构建命令:
"build": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts build'",
"build:staging": "REACT_APP_ENV=staging npm run build",
"build:prod": "REACT_APP_ENV=production npm run build",
.env.staging.js:
.env.staging.js:
REACT_APP_BASE_HREF=/staging
index.html:
index.html:
....
<base href="" + process.env.REACT_APP_API_URL />
....
这似乎不适用于索引.html。虽然类似的设置适用于JS文件
This doesn't seem to work in index.html. While similar setup works for JS files
(可能是因为JS文件被解析并捆绑到一个文件中,并且捆绑程序在该时间点读取值)
(Probably because JS files are parsed and bundled into a single file and the bundler reads the values at that point of time)
尝试过的事情:
index.html:
index.html:
< base href = process.env.REACT_APP_API_URL />
< base href = process.env.REACT_APP_API_URL />
< base href =%process.env。 REACT_APP_API_URL% />
(类似于PUBLIC_URL变量)
<base href="%process.env.REACT_APP_API_URL%" />
(similar to PUBLIC_URL variable)
与浏览器路由器一起设置basename属性也不能解决问题
Setting basename property along with Browser Router also does not solve the problem
推荐答案
此问题已解决。请按照以下步骤操作:
This problem was solved. Follow these steps:
- 在package.json中,将
主页
项设置为 - 在.env.staging文件中设置
PUBLIC_URL = / survey
- 无需使用
< base href>
。可以从HTML文件中删除 -
将样式表的链接更改为
- In package.json Set
homepage
key to""
- In .env.staging file Set
PUBLIC_URL=/survey
- No need to use
<base href>
. Can be removed from HTML file Change links for stylesheet to
< rel rel = stylesheet href =%PUBLIC_URL%/ vendor / bootstrap / css / bootstrap.min.css>
无需添加process.env
No need to add process.env
这篇关于使用环境变量设置基本href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!