Initialising projects with NPX
React Native has seen 3 new releases in just past month. Choosing to install react-native globally means that virtually every time a new project is initiated an upgrade has to be handled manually. Instead one might take advantage of the Node Package Executor (NPX) that ships with NPM since version 5.2.0. NPX can initiate a build using a tool like e.g. React Native CLI without prior necessity for global or local installation.
Syntax follows the template below:
npx <tool> <tool's_commands>
So, to initiate a project using React Native CLI one would run:
npx react-native init <project_name>
Then, the keyword npx comes before every script we wish to run inside the project’s directory. For example:
npx react-native run-android
NPX Algorithm
In Linux-like operating systems, the PATH variable is a list of folders that contain executable files, which thanks to being listed in the PATH can be run in the command line without having to specify their exact location. The directory of the installation of Nodejs gets added to the PATH, therefore binaries there located can be accessed using the command line.
When a command like
npx react-native init <project_name>
is run, the NPX will look into this folder in search of an executable file called “react-native”. If it is found, then React Native CLI and not NPX is used to build the project. This is to see if the tool is installed globally. If it is not, then NPX will search for react-native locally. That is at:
PROJECT_ROOT\node_modules\.bin
The same way that NPM locates executables from packages installed globally in the Nodejs installation folder, executables from packages installed locally end up in the .bin folder.
When react-native.cmd is present in .bin then it is used to build the project.
Finally, when react-native is not installed neither locally nor globally then NPX installs the latest version from the NPM registry and immediately after installation finishes runs the commands.
🛑 SAFETY CHECK 1
In conclusion, to use NPX one must ensure that react-native is not installed neither globally nor locally.
🛑 SAFETY CHECK 2
To avoid permission errors the command emulator should be run with administrative privileges.
🛑 SAFETY CHECK 3
Like NPM, NPX also uses the Cache folder for its installation process. The default location of the Cache folder is :
USERS\USER_NAME\AppData\Roaming\npm-cache\_cacache
NPX runs into an error when it encounters spaces in file paths, such as spaces separating first and last name in the username. To prevent that one may update the location of the Cache folder where space is replaced with ~1
npm config set cache "c://users/FIRST~1SECOND/AppData/Roaming/npm-cache" --global
To confirm change, one may check the global NPM configuration file which is located at:
Program Files\nodejs\etc\npmrc