reactjs - 在 package.json 中设置主页不会在构建时设置 PUBLIC_URL

标签 reactjs webpack package.json

遵循文档 here (Building for Relative Paths) ,因此在 package.json 中设置 homepage 字段不会在构建期间设置 PUBLIC_URL。

预期行为
%PUBLIC_URL%build/index.html应替换为在 package.json 的主页字段中设置的 URL。

package.json:

"homepage": "https://example.com",

构建/index.html:
<script type="text/javascript" src="https://example.com/static/js/main.ec7f8973.js">

实际行为
<script type="text/javascript" src="/static/js/main.ec7f8973.js">
%PUBLIC_URL%将被替换为空。

最佳答案

在 package.json 中设置 homepage 字段后,生成构建时会显示以下消息:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

这导致您的 实际行为 .

我需要有一个完整的元标签 URL,例如 og:image 和 twitter:image:src

Timer said :“除非您明确使用 PUBLIC_URL 环境变量,否则只会将 URL 的路径插入到 %PUBLIC_URL% 中。”

所以我创建了一个 .env 在我的应用程序的根目录中添加一个引用包主页中相同 url 的变量的文件:
REACT_APP_BASE_URL=https://example.com

在 index.html 中,我将 %PUBLIC_URL% 替换为 env 变量:
<meta property="og:image" content="%REACT_APP_BASE_URL%/img/facebook_1200x630.jpg" />

以及构建的结果:
<meta property="og:image" content="https://example.com/img/facebook_1200x630.jpg" />

我相信这就是你所需要的。

关于reactjs - 在 package.json 中设置主页不会在构建时设置 PUBLIC_URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50043369/

相关文章:

npm - npm 运行脚本中参数的 if-else

javascript - 如何在不安装 babel 本身的情况下直接从脚本标签使用 babel

reactjs - antd tabs 使用 react-router

javascript - webpack插件的EJS模板 'html-webpack-plugin'

jquery - NPM 忽略 package.json 中的 jQuery 版本

TypeScript 项目无法部署到针对 Node 12 或 14 的 App Engine,但适用于 Node 10

reactjs - react useEffect 方法上的箭头体式错误

javascript - 使用 React Context 和 useReducer 防止重新渲染待办事项应用程序中未更改的项目

webpack - 将 XHR 添加到 Vue JS webpack

npm - webpack-dev-server 不监视我的文件更改