Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT_APP_* vs NODE_PATH Environment Variables

What is the difference between a regular CRA environment variable (that MUST begin with REACT_APP_) and the NODE_PATH variable (that is used to avoid having to use relative paths for imports, ../../../foo etc.)

From my testing, no variables can be used unless they begin with REACT_APP, so how is the NODE_PATH variable not ignored like other variables that do not begin with REACT_APP?

like image 996
HahnSolo Avatar asked Dec 24 '22 06:12

HahnSolo


1 Answers

NODE_PATH is accessible because it's added in the Webpack configuration in react-scripts.

You can see the code that adds it here: https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-scripts/config/env.js#L61

You'll see in that file that you can also set NODE_ENV which sets which environment you are running in (e.g. development, staging, etc.) as well as PUBLIC_URL

To answer your question on the differences:

NODE_PATH allows you to use absolute paths for imports. For example, you can set your NODE_PATH to the following:NODE_PATH=src:src/components:src/containers and then in your React code you could write something like this: import Button from 'button' instead of import Button from '../../../button' as long as you have that module in one of the folders src, src/components, or src/containers because create-react app will look for the button module those folders. You wouldn't actually use the NODE_PATH variable in your React code that same way that you use REACT_APP_* variables. Basically, it tells your app where to look for modules.

REACT_APP_* variables are injected into your application at build time using the Webpack configuration from the file I linked to.

This: const GRAPHQL_URI = REACT_APP_GRAPHQL_URI

becomes this: const GRAPHQL_URI = https://example.com

if you have this in your .env file: REACT_APP_GRAPHQL_URI = https://example.com

like image 192
Jeff Appareti Avatar answered Jan 02 '23 00:01

Jeff Appareti