NPM is a node package manager, which is used for installing removing packages from the NPM repository link. You can publish your own packages there as well.
The content table:
#NPM the common functionality
Create a package.json file we use the command
1 |
npm init |
Install packages from a package.json file use
1 |
npm install |
You can install package to your project by doing this command
1 |
npm install config --save |
this will install a config package to the project and add it to the package.json file. Without –save it will not add to a package.json file. You can use shortage -s
We can install packages globally by using this commands
1 2 |
npm install nodemon -g npm install live-server -g |
it will put nodemon and live-server globally and they will be accessible anywhere from the command line.
You can add packages to the package.json devDependencies by using a –save-dev flag
1 |
npm install debug --save-dev |
it will add debug to the devDependencies
#How to use npm scripts
npm has a scripts section where we specify our own scripts, which will run by commands
npm start
npm run build
npm test
… etc
You can specify any your command and it will run by using npm run [your name of command]. Here is my example
1 2 3 4 5 6 |
"scripts": { "start": "VAR1=\"here is the text\" SOME_VAR=HELLO_WORLD NODE_CONFIG_DIR=./config node ./bin/www", "server": "nodemon index.js", "live": "live-server", "test": "echo \"Error: no test specified\" && exit 1" }, |
Commands:
- npm start
- npm run server
- npm run live
- npm test
npm start – The command will specify a few node.js environment variables like VAR1, SOME_VAR, NODE_CONFIG_DIR and it will run the script ./bin/www by using this command node ./bin/www. Here is a code of ./bin/www
1 2 3 4 5 |
#!/usr/bin/env node console.log('process.env.VAR1 = ', process.env.VAR1); console.log('process.env.SOME_VAR = ', process.env.SOME_VAR); console.log('process.env.NODE_CONFIG_DIR = ', process.env.NODE_CONFIG_DIR); |
and we’ve got the output
1 2 3 4 5 6 7 8 9 |
neo@neo:~/node.js/React/test-npm-scripts$ npm start > test-npm-scripts@1.0.0 start /home/neo/node.js/React/test-npm-scripts > VAR1="here is the text" SOME_VAR=HELLO_WORLD NODE_CONFIG_DIR=./config node ./bin/www process.env.VAR1 = here is the text process.env.SOME_VAR = HELLO_WORLD process.env.NODE_CONFIG_DIR = ./config neo@neo:~/node.js/React/test-npm-scripts$ |
npm run server – it will run a nodemon server
npm run live – it will run a live-server
npm test – it will run a tests
the end