使用PUBLIC_URL创建反应应用程序构建

Gul*_*ith 44 javascript reactjs create-react-app

我尝试着

PUBLIC_URL=http://example.com npm run build
Run Code Online (Sandbox Code Playgroud)

使用最新的create-react-script构建的项目.

但是,public/index.html中出现的%PUBLIC_URL%将替换为空字符串,而不是期望值PUBLIC_URL.

public/index.html包含类似的代码

<script src="%PUBLIC_URL%/static/js/jarvis.widget.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

搜索互联网和堆栈溢出的时间表明,关于PUBLIC_URL的文章很少.我从git hub克隆了create-react-app并且一直在浏览代码,但还没有被开悟.

有没有人对我做错了什么有任何建议?

red*_*bmk 36

如果其他答案对你不起作用,那么还有一个homepage字段package.json.运行后,npm run build您应该收到如下消息:

The project was built assuming it is hosted at the server root.
To override this, specify the homepage in your package.json.
For example, add this to build it for GitHub Pages:

  "homepage" : "http://myname.github.io/myapp",
Run Code Online (Sandbox Code Playgroud)

您只需将其添加为其中一个根域package.json,例如

{
  // ...
  "scripts": {
    // ...
  },
  "homepage": "https://example.com"
}
Run Code Online (Sandbox Code Playgroud)

当它成功设置时,或者通过homepagePUBLIC_URL,你应该得到这样的消息:

The project was built assuming it is hosted at https://example.com.
You can control this with the homepage field in your package.json.
Run Code Online (Sandbox Code Playgroud)

  • 当我回到react-scripts 3.3.0 时,这对我有用。 (2认同)

Vai*_*hal 14

像我这样的人正在构建中寻找这样的东西:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
Run Code Online (Sandbox Code Playgroud)

然后设置https://dsomething.cloudfront.nethomepagein package.json将不起作用。

1.快速解决方案

像这样构建项目:
(Windows)

set PUBLIC_URL=https://dsomething.cloudfront.net&&npm run build
Run Code Online (Sandbox Code Playgroud)

(Linux / Mac)

PUBLIC_URL=https://dsomething.cloudfront.net npm run build
Run Code Online (Sandbox Code Playgroud)

你会得到

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
Run Code Online (Sandbox Code Playgroud)

在您建立的index.html中

2.永久和推荐的解决方案

.env在项目根目录(package.json所在的位置)创建一个名为的文件。
在此文件中编写以下内容(URL两端不加引号):

PUBLIC_URL=https://dsomething.cloudfront.net
Run Code Online (Sandbox Code Playgroud)

像往常一样构建您的项目(npm run build),
这还将生成带有以下内容的index.html:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
Run Code Online (Sandbox Code Playgroud)

3.奇怪的解决方案

将此添加到您的package.json
“主页”中:“ http://://dsomething.cloudfront.net ”,

然后将使用以下命令生成index.html:

<script type="text/javascript" src="//dsomething.cloudfront.net/static/js/main.ec7f8972.js">
Run Code Online (Sandbox Code Playgroud)

基本上与以下内容相同:

<script type="text/javascript" src="https://dsomething.cloudfront.net/static/js/main.ec7f8972.js">
Run Code Online (Sandbox Code Playgroud)

以我的理解。

Github问题 Github评论


Tob*_*oby 13

这不是PUBLIC_URL变量的使用方式.根据文档,您可以在HTML中使用PUBLIC_URL:

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

或者在你的JavaScript中:

render() {
  // Note: this is an escape hatch and should be used sparingly!
  // Normally we recommend using `import` for getting asset URLs
  // as described in “Adding Images and Fonts” above this section.
  return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
}
Run Code Online (Sandbox Code Playgroud)

PUBLIC_URL不是您设置为您选择的值的东西,它是一种在Webpack的构建系统之外的部署中存储文件的方法.

要查看此内容,请运行您的CRA应用并将其添加到src/index.js文件中:

console.log('public url: ', process.env.PUBLIC_URL)

您将看到该URL已存在.

阅读CRA文档中的更多内容.

  • “PUBLIC_URL 不是您设置为您选择的值”。你确定吗?https://create-react-app.dev/docs/advanced-configuration -&gt;“您可以通过在 shell 中或使用 .env 设置环境变量来调整各种开发和生产设置”。PUBLIC_URL -&gt;“您可以使用此变量强制将资产逐字引用到您提供的 URL(包括主机名)。当使用 CDN 托管您的应用程序时,这可能特别有用。” (2认同)

won*_*suc 11

如果您看到源代码,它们会检查是否process.env.NODE_ENV === 'development'返回true,并且它们会自动删除主机 URL 并仅返回路径。

例如,如果您设置如下

PUBLIC_URL=http://example.com/static/
Run Code Online (Sandbox Code Playgroud)

他们将移除http://example.com并仅返回/static

但是,由于您只设置根 URL,如http://example.com,它们只会返回一个空字符串,因为您的 URL 字符串中没有子路径。

仅当您调用 时才会发生这种情况react-scripts start,并且如果您调用react-scripts buildthen isEnvDevelopmentwill false,因此它将仅返回http://example.com您在文件中设置的内容.env

这是getPublicUrlOrPath.js的源代码。

/**
 * Returns a URL or a path with slash at the end
 * In production can be URL, abolute path, relative path
 * In development always will be an absolute path
 * In development can use `path` module functions for operations
 *
 * @param {boolean} isEnvDevelopment
 * @param {(string|undefined)} homepage a valid url or pathname
 * @param {(string|undefined)} envPublicUrl a valid url or pathname
 * @returns {string}
 */
function getPublicUrlOrPath(isEnvDevelopment, homepage, envPublicUrl) {
  const stubDomain = 'https://create-react-app.dev';

  if (envPublicUrl) {
    // ensure last slash exists
    envPublicUrl = envPublicUrl.endsWith('/')
      ? envPublicUrl
      : envPublicUrl + '/';

    // validate if `envPublicUrl` is a URL or path like
    // `stubDomain` is ignored if `envPublicUrl` contains a domain
    const validPublicUrl = new URL(envPublicUrl, stubDomain);

    return isEnvDevelopment
      ? envPublicUrl.startsWith('.')
        ? '/'
        : validPublicUrl.pathname
      : // Some apps do not use client-side routing with pushState.
        // For these, "homepage" can be set to "." to enable relative asset paths.
        envPublicUrl;
  }

  if (homepage) {
    // strip last slash if exists
    homepage = homepage.endsWith('/') ? homepage : homepage + '/';

    // validate if `homepage` is a URL or path like and use just pathname
    const validHomepagePathname = new URL(homepage, stubDomain).pathname;
    return isEnvDevelopment
      ? homepage.startsWith('.')
        ? '/'
        : validHomepagePathname
      : // Some apps do not use client-side routing with pushState.
      // For these, "homepage" can be set to "." to enable relative asset paths.
      homepage.startsWith('.')
      ? homepage
      : validHomepagePathname;
  }

  return '/';
}
Run Code Online (Sandbox Code Playgroud)


小智 6

看看文档.你可以有一个.env文件来获取PUBLIC_URL

虽然你应该记住它用于什么 -

您可以使用此变量强制资源逐字引用到您提供的URL(包括主机名).当使用CDN托管您的应用程序时,这可能特别有用.


Tob*_*byG 6

如此处所述, create-react-app 只会导入以 开头的环境变量REACT_APP_,因此PUBLIC_URL,我相信,正如 @redbmk 提到的,来自文件homepage中的设置package.json


Jim*_*yLv 5

实际上,在不同的操作系统之间,设置环境变量的方式是不同的。

Windows(cmd.exe)

set PUBLIC_URL=http://xxxx.com&&npm start
Run Code Online (Sandbox Code Playgroud)

(注意:缺少空格是有意的。)

Linux,macOS(Bash)

 PUBLIC_URL=http://xxxx.com npm start
Run Code Online (Sandbox Code Playgroud)

推荐: cross-env

{
  "scripts": {
    "serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
  }
}
Run Code Online (Sandbox Code Playgroud)

参考:create-react-app / README.md#在主机上的外壳中添加临时环境变量facebook.cubaincubator / create-react-app

  • 为什么“build”脚本中有“npm start”? (2认同)