droledenom
droledenom

Reputation: 225

replace npm start by what it redirects to

I am testing a code and in the .json file there is:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build"
}

The code works well when I run

npm start

in the console.

But npm start shall be a shortcut. If I write:

react-scripts start

instead in the console it doesn't work. My error message is

react-scripts: command not found 

Why? It is not equivalent? And if react-scripts is not found how does using npm start works?

Thank you

Upvotes: 0

Views: 738

Answers (1)

k0pernikus
k0pernikus

Reputation: 66817

Any defined npm script exexcuted by npm run will look for executionable binaries from with

cd your_project
./node_modules/.bin

folder first. You can also see its full path via:

npm bin

These binaries are coming from your project's defined dependencies from the package.json via npm install.

npm run start is hence euquivalent to running:

./node_modules/.bin/react-scripts start

When you try to run

react-scripts start

on its own, you terminal will only look up your system's PATH and try to find it there.

echo $PATH

So if you have react-scripts only installed locally and not globally, it won't find the executable binary, and hence fail.

If you want to run it globally, you have to install it globally:

npm install -g react-scripts
which react-scripts
~/.nvm/versions/node/v7.10.0/bin/react-scripts //

and ~/.nvm/versions/node/v7.10.0/bin is part of my PATH.


Sidenotes:

I prefer having each project define its own dependencies with their specific version locally and only use that. As you might have multiple projects dependending on different version of a binary.

And if you consistently use the one defined in the package.json, you won't run into problems.

It also prevents "works on my machine" problems with co-workers when your npm script consistently rebuilds the state.

With npm it's a bit messy as you either define all the dependencies libraries you want to use in the npm scripts, or you have to run each command like:

$(npm bin)/yourCmd

Since I also like using yarn as my npm replacement, I grew fond of its default to always look into the project's bin folder in order to execute a cmd via:

yarn yourCmd
$ "/home/philipp/my-project/node_modules/.bin/yourCmd"

Upvotes: 1

Related Questions