![](/img/trans.png)
[英]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.