Skip to content

Instantly share code, notes, and snippets.

@amitozdeol
Last active April 26, 2020 12:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitozdeol/4c3edcb377b4f0662706e0c96c4c1b9f to your computer and use it in GitHub Desktop.
Save amitozdeol/4c3edcb377b4f0662706e0c96c4c1b9f to your computer and use it in GitHub Desktop.
NPM advance commands
  1. Use npx instead of npm
    1. Instead of using node ./node_modules/typescript/bin/tsc use npx tsc
  2. Pass parameter in npm
    1. If we have a script called tsc to run typescript, tsc --build --clean --> npm run tsc -- --build --clean
  3. Shortcut scripts
    1. npm test --> npm run test
    2. npm start --> npm run start
    3. npm stop --> npm run stop
  4. Pre/Post script hooks - NPM have pre and post scripts that run before and after a script is run
    1. If we have 3 script in package.json "preecho": "echo pre", "echo": "echo now" "postecho": "echo post", it will run all 3 scripts when run --> npm run echo

Running Scripts in Parallel

Say you want to run both watch scripts at the same time as you are working on both your CSS and JS files. Running npm run watch:css && npm run watch:js isn’t going to work, as these commands are run in sequence (i.e. watch:js won’t run until watch:css is finished). So how do we run these scripts in parallel (at the same time)?

We can achieve this using another package called npm-run-all:

    npm install npm-run-all --save-dev

npm-run-all has a --parallel flag that allows us to run groups of tasks in parallel. So let’s create a new watch script:

"scripts": {
    ...
    "watch": "npm-run-all --parallel watch:*"
    
}

NPM config variables

Npm has a config directive for your package.json. This lets you set arbitrary values which can be picked up as environment variables in your scripts.

"config":{
    "localdevenv": "development"
},
"scripts": {
    "dev": "cross-env NODE_ENV=$npm_package_config_localdevenv npm run build",
    "watch": "cross-env NODE_ENV=$npm_package_config_localdevenv webpack 
    ...
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment