Every day, millions of developers use NPM or YARN to build projects. Running commands like NPM init or NPX create-Response-app is almost the preferred way to build JS projects, whether for client or server, or desktop applications.
But NPM is more than just initializing projects or installing packages. In this article, we’ll look at 13 techniques for getting the most out of NPM: from simple shortcuts to custom scripts.
Since many of us use NPM every day, even small time savings can make a significant difference in the long run. These tips are aimed at beginner and intermediate developers, but even if you’re an experienced developer, I hope you’ll still find a feature or two that you haven’t encountered before.
The main content
Learn basic shortcuts
Set the default NPM init property
Make scripts cross-platform compatible
Running scripts in parallel
Run the script in a different directory
Delay running the script until the port is ready
List and select the available scripts
Before and after scripts
Control the application version
Edit package.json from the command line
Automatically set up and open your Github library
Custom NPM init script
Commit your first Commit to GitHub using a custom NPM init script
1. Learn basic shortcuts
Let’s start with the basics, and learning the most common NPM shortcuts will save a lot of time in the long run.
Installation – General: NPM install, short: NPM I.
Tests – General: NPM test, short: NPM T.
Help – General: NPM –help, short: npm-h.
Global flags – General: –global, short: -g.
Save as development dependency – general: -save-dev, short: -d.
NPM init Default value – General: NPM init –yes or NPM init –force, short: NPM init -y or NPM init -f
We know to use -save or -s to save packages, but this is now the default. To install a package without saving it, use the — no-save flag.
Less common shortcut keys
There are also some less common shortcuts, such as:
Install package information is added to optionalDependencies – General: –save-optional, short: -o.
Install the specified module version precisely – General: –save-optional, short: -o.
If you need to save an NPM package locally, or select a set of available packages through a single file download, you can bundle them together using –save-bundle or -b and get bundles using NPM pack.
Shortcuts to roots
The. Symbol is typically used to indicate the root directory of an application, the application entry point in NPM terminology, the value of “main” in package.json
{ “main”: “index.js”}
This shortcut can also be used like NPX create-react-app. Such an order. Therefore, instead of creating a new my-app directory using NPX create-react-app my-app, run NPX create-react-app.
2. Set the default NPM init property
When running NPM init to start a new project, you may find yourself entering configuration details again and again. If so, you might be in charge of the project. Sometimes to save time, you can set default values for these fields, as shown below:
npm config set init.author.name “Joe Bloggs”npm config set init.author.email “[email protected]”npm config set init.author.url “Joebloggs.com”npm config set init.license “MIT”
To check that these properties are correctly added, type NPM config Edit at the terminal to view the configuration file information. Of course, j can also edit information directly in the open configuration file. To edit global NPM Settings, use NPM config edit -g.
To reinitialize the default Settings, use the following script. The first line replaces the configuration file with an empty string, and the second line repopulates the configuration file with default Settings.
echo “” > $(npm config get userconfig)npm config edit
The above script resets the user defaults and the following script resets the global defaults
echo “” > $(npm config get globalconfig)npm config –global edit
3. Make scripts cross-platform compatible
Any code that runs on the command line runs the risk of compatibility issues, especially between Windows and UniX-based systems, including Mac and Linux. This is not a problem if you only work on specific projects, but in many cases cross-platform compatibility is essential: any open source or collaborative project, as well as sample and tutorial projects, should work regardless of the operating system.
Thankfully, the solution is simple. There are several options to choose from, but the cross-env works best. Install it as a development dependency using NPM I-d cross-env. Then include the keyword cross-env before any environment variables, like this:
{ “scripts”: { “build”: “cross-env NODE_ENV=production webpack –config build/wepack.config.js” }}
Cross-env is the most seamless way to achieve cross-platform compatibility, but there are two other popular tools that can help with cross-platform compatibility:
Rimraf can be installed to run cross-platform scripts globally
ShellJS is a portable implementation of Unix shell commands on the Node.js API.
4. Run scripts in parallel
You can use && to run two or more processes in sequence. But what about running scripts in parallel? To do this, we can choose from a variety of NPM packages. Concurrent and NPM-run-all are the most popular solutions.
Develop dependencies first with an NPM I-D CONCURRENTLY installation. Then add it to the script in the following format:
{ “start”: “concurrently “command1 arg” “command2 arg””}
5. Run the scripts in different directories
Sometimes you have an application with multiple package.json files in different folders. Instead of navigating to a different folder each time you want to run the script, there are two ways to do this.
The first is to manually CD and run the corresponding command:
cd folder && npm start && cd ..
But there is a more elegant solution, which uses the –prefix flag to specify the path:
npm start –prefix path/to/your/folder
Here is an example of this solution in a working application where we want to run NPM start on the front end (in the client directory) and the back end (in the server directory).
“start”: “concurrently “(npm start –prefix client)” “(npm start –prefix server)””,
6. Delay running the script until the port is ready
Often, during the development of a full-stack application, we might want to start both the server and the client. The Wait-on node module provides a convenient way to ensure that processes occur only when certain processes are ready: in our case, we have a specific port.
For example, this is the dev script I used in the Electron project using the React front end. Used simultaneously, the script loads the presentation layer and the Electron window in parallel. However, with wait-on, the Electron window will only open if http://localhost:3000 is started.
“dev”: “concurrently “cross-env BROWSER=none npm run start” “wait-on http://localhost:3000 && electron .””,
Also, React opens a browser window by default, but this is not necessary for Electron development. We can disable this behavior by passing the environment variable BROWSER= None.
7. List and select the available scripts
Listing the scripts available in the package.json file is simple: Just go to the root of the project and type NPM run in the terminal.
But there is a more convenient way to get a list of scripts that you can run immediately: to do this, install the NTL (NPM Task List) module globally:
npm i -g ntl
Then run the NTL command in the project folder to get a list of available scripts and choose one to run.
8. Run the before and after scripts
You’re probably familiar with scripts like Prebuild and Postbuild, which allow you to define code to run before or after a build script. But in fact, pre and POST can be added before any script, including custom scripts.
This not only makes your code cleaner, but also allows you to run pre and POST scripts separately.
9. Control the application version
Instead of manually changing the version of your application, NPM provides some useful shortcuts to do this. To add a version, run NPM Version plus major, minor or patch ‘:
// 1.0.0 NPM version patch// 1.0.1 NPM version minor// 1.1.0 NPM version Major // 2.0.0
Depending on how often your application is updated, you can save time by increasing the version number at each deployment, using the following script:
{ “predeploy”: “npm version patch”}
Edit package.json from the command line
Package. json is a regular JSON file, so you can edit it from the command line using the tool library JSON. This provides another new way to modify package.json, allowing you to create shortcuts that exceed the default values. Global installation:
npm install -g json
You can then use it for in-place editing with -i. For example, to add a new script “foo” with a value of “bar”, write:
json -I -f package.json -e ‘this.scripts.foo=”bar”‘
Automatically set up and open your Github library
If you have “repository” in the package.json file, you can open it in the default browser by typing NPM repo.
If your project is already connected to a remote repository and you have Git installed on the command line, you can use this command to find your connection repository.
git config –get remote.origin.url
Better yet, if you follow the tips above and install the JSON module, you can use the script below to automatically add the correct repository to package.json
json -I -f package.json -e “this.repository=”$(git config –get remote.origin.url)””
12. Customize NPM init scripts
Let’s go one step further and use our own NPM init script, which accepts the GitHub repository URL and automatically pushes our first commit. In this tip, we discuss how to create a custom NPM init script. In the next (and final) tip, we’ll merge Git.
The NPM init script can be edited by redirecting to the.npm-init.js file in the home directory. (On Windows, it’s usually C /Users/< username >, on Mac, it’s /Users/< username >).
Let’s start by creating a.nMM-init.js file in our home directory. To ensure that NPM init is pointed to the correct file, run:
npm config set init-module ~.npm-init.js
Before integrating Git, there is a simple.npm-init.js file that emulates the problems of default NPM init.
module.exports = { name: prompt(‘package name’, basename || package.name), version: Prompt (‘version’, ‘0.0.0’), decription: prompt(‘description’, ”), main: prompt(‘entry point’, ‘index.js’), repository: prompt(‘git repository’, ”), keywords: prompt(function (s) { return s.split(/\s+/) }), author: prompt(‘author’, ‘Joe Bloggs [email protected] (joebloggs.com)’), license: prompt(‘license’, ‘ISC’)}
Each issue follows the nameInPackage pattern :prompt(‘nameInPrompt’,’defaultValue’). To set the values without problems by default, simply remove the prompt method.
To return to the default Settings, simply delete.npm-init.js.
Commit your first Commit to GitHub using a custom NPM init script
In order to merge git commands into the.npm-init.js file, you need a way to control the command line. To do this, we can use the child_process module. Introduce it at the top of the file, because we only need the execSync function, so we can get it ourselves using the destructor assignment syntax:
const { execSync } = require(‘child_process’);
I also created a helper function that prints the result of the function to the console:
function run(func) { console.log(execSync(func).toString())}
Finally, we’ll be prompted for the GitHub repository URL, and if provided, we’ll generate the readme.md file and launch our first commit.
repository: prompt(‘github repository url’, ”, function (url) { if (url) { run(‘touch README.md’); run(‘git init’); run(‘git add README.md’); run(‘git commit -m “first commit”‘); run(git remote add origin ${url}); run(‘git push -u origin master’); } return url; })
In general, the.npm-init.js file looks like this:
const { execSync } = require(‘child_process’); function run(func) { console.log(execSync(func).toString())}module.exports = { name: Prompt (” package name “, the basename | | package. The name), version: prompt (‘ version ‘and’ 0.0.0), decription: prompt(‘description’, ”), main: prompt(‘entry point’, ‘index.js’), keywords: prompt(function (s) { return s.split(/\s+/) }), author: prompt(‘author’, ‘Joe Bloggs [email protected] (joebloggs.com)’), license: prompt(‘license’, ‘ISC’), repository: prompt(‘github repository url’, ”, function (url) { if (url) { run(‘touch README.md’); run(‘git init’); run(‘git add README.md’); run(‘git commit -m “first commit”‘); run(git remote add origin ${url}); run(‘git push -u origin master’); } return url; }}),
Package. Json file:
{“name”: “Custom NPM init”, “version”: “0.0.0”, “decription”: “A test project, to demonstrate a custom npm init script.”, “main”: “index.js”, “keywords”: [], “author”: “Joe Bloggs [email protected] (joebloggs.com)”, “license”: “ISC”, “repository”: { “type”: “git”, “url”: “Git+https://github.com/JoeBloggs/custom.git”}, “bugs” : {” url “:” github.com/JoeBloggs/c…” }, “homepage” : “github.com/JoeBloggs/c…” }
You can also take this one step further by incorporating the GitHub API so that you don’t need to create a new repository, and leave that up to you.
Overall, hopefully this article gave you an idea of what NPM can achieve and showed you some ways to improve your productivity — whether you know common shortcuts, or by taking full advantage of the package.json script, or writing a custom version of NPM init.