pea-sea
pea-sea

Reputation: 189

How to run a production build of my react app locally?

My package.json has the following script:

"build": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts build'"

When I run yarn build I get the following error:

sh: .env.: No such file or directory

The .env file is in the top level of my project directory as expected. Any ideas?

Upvotes: 4

Views: 17279

Answers (2)

joeytwiddle
joeytwiddle

Reputation: 31285

Copy or rename .env.foo to .env.foo.sh and add export at the beginning of each line, like this:

export REACT_APP_HEADER_COLOR="#f66"

Source this new shellscript instead of the old env file:

"sh -ac '. .env.${REACT_APP_ENV}.sh; react-scripts build'"

Now the variables will be successfully passed down to the build process, for it to use.

Why?

That is just how shells work. An environment variable loaded into the current shell (with source or . or assignment) is only passed down to the child, if it is exported:

$ FOO=foo
$ sh -c 'echo $FOO'

$ export FOO=foo
$ sh -c 'echo $FOO'
foo

Note that these one-line shortcuts also export automatically/implicitly:

$ BAR=bar sh -c 'echo $BAR'
bar
$ env BAR=baz sh -c 'echo $BAR'
baz

(I suspect this hidden behaviour is a frequent source of confusion.)

Upvotes: 1

user9572013
user9572013

Reputation:

You could also use the NODE_ENV variable, it gives you the environment mode.

I don't know if you're using create-react-app, but if you are (once you have built your app), you can use serve to run the production version:

$ npm install -g serve

$ serve -s build

Upvotes: 3

Related Questions