[英]Unable to get env variables in public/index.html for react app
[英]Get public URL in index.html after build
我有一个使用命令npx npx create-react-app my-app
的reactjs应用npx create-react-app my-app
,我使用yarn build
构建了我的项目
包json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
构建完应用程序后,index.html如下所示(它具有所有静态文件的绝对路径),
<script type="text/javascript" src="/static/js/main.af2bdfd5.js"></script>
<link href="/static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="/favicon.ico">
我希望这些来源如下所示(需要提供公共网址)
<script type="text/javascript" src="http://localhost:3000/static/js/main.af2bdfd5.js"></script>
<link href="http://localhost:3000/static/css/main.097da2df.css" rel="stylesheet">
<link rel="shortcut icon" href="http://localhost:3000/favicon.ico">
我尝试将PUBLIC_URL
和homepage
添加到package.json中,但是没有用。
只需在链接的href中使用%PUBLIC_URL%
,只有当公用文件夹中存在这些文件时,它才会获取文件。
将您的文件在public
文件夹中,让我们假设该文件是您要访问您的图标,它的名字是icon.ico
<link rel="shortcut icon" href="%PUBLIC_URL%/icon.ico">
您无需为文件添加绝对URL,只需在index.html中使用%PUBLIC_URL%
。
注意 :您不需要将PUBLIC_URL添加到package.json
。 它已分配给公用文件夹。
找到了解决方案,
我使用dotenv
设置环境变量。 下面给出了实现该解决方案的步骤。
1)安装dotenv
软件包。
npm i dotenv
2)尽早在应用程序中,要求并配置dotenv。
require('dotenv').config()
3)在项目的根目录中创建一个.env
文件。 在新行上以NAME=VALUE
的形式添加特定于环境的变量。
PUBLIC_URL=http://192.168.8.100:3000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.