Starting the local development environment with the NPM run dev command is quite normal in front-end development. After typing a command like NPM run XXX, how do you trigger the build commands of various build tools and start the Node service?

First we know that Node, as a JavaScript runtime, can run.js files as scripts, like this:

node index.js
Copy the code

When we use NPM to manage projects (or yarn), a package.json file is generated in the root directory, where the scripts property is used to configure NPM run XXX. For example, I have the following configuration:

// package.json
{
  // ...
  "scripts": {
    "start": "node ./src/index.js"."build": "react-scripts build",},// ...
}
Copy the code

When NPM start is executed, which for NPM is equivalent to NPM run start, it is mapped to the start command under the scripts property, that is

npm start
# is equivalent to
npm run start
# is equivalent to
node ./src/index.js
Copy the code

/ SRC directory to execute the index.js file./ SRC directory.

To run the NPM run build command, run the react-scripts build command. This command is configured by default when creating a React project using create-react-app. Unlike Node, React-scripts is not installed globally, so how can it be executed directly?

After NPM install, the node_modules directory for create-react-app (and for vue- CLI) will look like this:

As you can see in the figure, there is a.bin directory, which is not any NPM package. Every file in the directory has a small arrow on the right (VS Code) to indicate that it is a soft link, and when you open the file you will see #! /user/bin/env node, indicating that this is a script executed using node.

React-scripts build (NPM run build) {react-scripts build (NPM run build); But NPM will go to./node_modules/.bin and find the react-scripts.js file to execute as the Node script. /node_modules/.bin/react-scripts build (the last build is passed as an argument).

npm run build
# is equivalent to
./node_modules/.bin/react-scripts build
Copy the code

As mentioned earlier, react-scripts is a soft link, so where and how does it point to?

The react-scripts package can be found in node_modules, and its directory structure and package.json are as follows:

/bin/react-scripts.js is declared as bin by package.json. /node_modules/. Bin, and NPM automatically adds node_modules/. Bin to $PATH. This allows you to run and develop dependencies directly as a command without having to install them globally.

If NPM install -g XXX is used to install the package, the bin file will be added to the global installation, such as create-react-app and vue-cli. You can create projects directly using commands such as vue-cli projectName.