[英]Get public URL in index.html after build
I have a reactjs app created with command npx create-react-app my-app
, and I build my project using yarn build
我有一个使用命令npx
npx create-react-app my-app
的reactjs应用npx create-react-app my-app
,我使用yarn build
构建了我的项目
package json: 包json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Once I build the app index.html looks like below (It has absolute paths for all the static files), 构建完应用程序后,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">
I want to have those sources looks like below (need to give a public URL) 我希望这些来源如下所示(需要提供公共网址)
<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">
I have tried adding PUBLIC_URL
and homepage
to package.json but it didn't work. 我尝试将
PUBLIC_URL
和homepage
添加到package.json中,但是没有用。
Just use %PUBLIC_URL%
in your link's href and it will fetch the files only if those files are present in the public folder. 只需在链接的href中使用
%PUBLIC_URL%
,只有当公用文件夹中存在这些文件时,它才会获取文件。
Place your files in the public
folder and lets assume the file is your icon which you want to access and its name is icon.ico
将您的文件在
public
文件夹中,让我们假设该文件是您要访问您的图标,它的名字是icon.ico
<link rel="shortcut icon" href="%PUBLIC_URL%/icon.ico">
You don't need to put the absolute url for your files and can just use %PUBLIC_URL%
in index.html. 您无需为文件添加绝对URL,只需在index.html中使用
%PUBLIC_URL%
。
Note : You don't need to add PUBLIC_URL to package.json
. 注意 :您不需要将PUBLIC_URL添加到
package.json
。 It's assigned to the public folder already. 它已分配给公用文件夹。
Found a solution, 找到了解决方案,
I used dotenv
to set the environment variable. 我使用
dotenv
设置环境变量。 Steps to implement the solution is given below. 下面给出了实现该解决方案的步骤。
1) Install dotenv
package. 1)安装
dotenv
软件包。
npm i dotenv
2) As early as possible in the application, require and configure dotenv. 2)尽早在应用程序中,要求并配置dotenv。
require('dotenv').config()
3) Create a .env
file in the root directory of the project. 3)在项目的根目录中创建一个
.env
文件。 Add environment-specific variables on new lines in the form of NAME=VALUE
. 在新行上以
NAME=VALUE
的形式添加特定于环境的变量。
PUBLIC_URL=http://192.168.8.100:3000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.