如何仅在 create-react-app 的生产构建文件中包含 JavaScript 库?

How to include JavaScript libraries only in production build files of create-react-app?

我正在尝试添加 JavaScript 库,该库仅包含在 create-react-app 生成的生产构建文件中。

最好的方法是什么?

具体来说,我正在尝试包含 Rollbar.js 客户端错误监控库。我不希望每次在 development/testing 环境中出现错误时触发它,所以我只希望它包含在 运行 npm run build.

时生成的文件中

您可以使用环境变量。例如:

if (process.env.NODE_ENV === 'production') {
  const Rollbar = require('rollbar');
}

您可以像使用 NODE_ENV var 一样调用构建命令,如下所示:

NODE_ENV="production" npm run build

值得注意的是,您不能有条件地使用 import 语法。

tpdietz 提供的答案非常好,可能适用于许多图书馆。

但是,我尝试使用的这个特定库 (Rollbar) 需要在任何其他 JavaScript(例如 React 和 ReactDOM)之前加载,否则它无法捕获所有错误。由于那些其他库是通过 import 语句加载的,因此我不能在 index.js.

顶部的它们前面使用 require 语句

我找到的解决方案(感谢GitHub user rokob with the Rollbar.js project) is to reference the NODE_ENV variable from within the index.html file, as described here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#referencing-environment-variables-in-the-html

在我的 index.html 文件的顶部,在 <script> 标记中,我可以将变量设置为 %NODE_ENV%。 create-react-app 的构建过程将自动解析该变量并插入环境名称,例如"production" 或 "development",在最终的 index.html 文件中。然后,我可以在执行任何内联 JavaScript.

之前检查该变量是否等于 "production"

示例index.html

<!doctype html>
<html lang="en">
<head>
  <script>
    var environment = "%NODE_ENV%";
    if (environment === "production") {
      // code here will only run when index.html is built in production environment
      // e.g. > $ NODE_ENV="production" npm run build
    }
  </script>

在 Rollbar.js 的特定情况下,我只需要传递一个带有环境名称的配置参数,因此不需要 if 语句:

var _rollbarConfig = {
  ...
  enabled: ('%NODE_ENV%' === 'production')  //returns true if 'production'
  ...
};

这是 Github 上的问题,rokob 给我提供了这个解决方案:https://github.com/rollbar/rollbar.js/issues/583