如何检测 Gatsby 是否为构建输出提供服务?

How to detect that is Gatsby serving the build output?

我想知道这是否可能以及如何检测代码 运行 是否是由 gatsby serve 提供的 gatsby 的 build 输出。 当我启动 gatsby serve 时,浏览器在 localhost:9000/ 上打开,我需要根据某种环境变量或其他方式更改代码。我正在寻找最惯用的方法来做到这一点,如果可能的话,不要像阅读 window.location 对象这样的黑客攻击。 提前致谢

当您 gatsby build 时,Gatsby 在项目的 public 文件夹中创建项目的生产就绪构建。这意味着您可以使用 public 文件夹并将代码部署到 http 服务器。您不能 "detect" 此代码的任何特殊属性。 gatsby buildgatsby build.

我看到的唯一方法是在 gatsby serve 时检测标准 gatsby serve 端口号 :9000 的使用。见 Mozilla docs.

你可以从 Gatsby 实现的 reach/router API 得到 location props。我不确定它是否实现了 Mozilla 文档中提到的相同方法。你应该试试这个。

const index = ({ location }) => {

  console.log(location.port);

  // ...
}

作为替代方案,您可以按照 answer.

中所述解析 URL 字符串