MattSidor
MattSidor

Reputation: 2739

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

I'm trying to add a JavaScript library that is only included in the production build files generated by create-react-app.

What's the best way to do this?

Specifically, I'm trying to include the Rollbar.js client-side error monitoring library. I don't want it triggering every time I get an error in development/testing environments, so I only want it included in the files that are generated while running npm run build.

Upvotes: 3

Views: 5552

Answers (2)

MattSidor
MattSidor

Reputation: 2739

The answer provided by tpdietz is a very good one and would probably work well for many libraries.

However, this specific library I'm trying to use (Rollbar) needs to be loaded before any other JavaScript (e.g. React and ReactDOM), or else it can't capture all errors. Since those other libraries are loaded via import statements, I can't use a require statement in front of them at the top of index.js.

The solution I found (thanks to 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

At the top of my index.html file, in a <script> tag, I can set a variable to %NODE_ENV%. The build process for create-react-app will automatically parse that variable and insert the name of the environment, e.g. "production" or "development", in the final index.html file. Then, I can check to see if that variable is equal to "production" before executing any inline JavaScript.

Example 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>

In the specific case of Rollbar.js, I just needed to pass a config parameter with the environment name, so no if statement is necessary:

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

Here is the issue on Github where rokob gave me this solution: https://github.com/rollbar/rollbar.js/issues/583

Upvotes: 9

tpdietz
tpdietz

Reputation: 1368

You can use environment variables. For example:

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

You can invoke the build command like with a NODE_ENV var like so:

NODE_ENV="production" npm run build

Its worth noting you cannot conditionally use import syntax.

Upvotes: 4

Related Questions