13 npm rapid development skills

Source | http://www.fly63.com/article/detial/4015

Every day, millions of developers use npm or yarn to build projects. Running commands such as npm init or npx create- response -app is almost the preferred way to build js projects, whether it is client-side, server-side, or desktop applications.

But npm is not just about initializing projects or installing packages. In this article, we will introduce 13 techniques of npm to make the most of npm: from simple shortcuts to custom scripts.

Since many of us use npm every day, even a small amount of time saved will have a significant impact in the long run. These tips are for beginners and intermediate developers, but even if you are an experienced developer, I hope you can still find one or two features you haven't encountered before.

primary coverage

  • Learn basic shortcuts

  • Set default npm init attribute

  • Make scripts cross platform compatible

  • Running scripts in parallel

  • Run scripts in different directories

  • Delay running the script until the port is ready

  • List and select available scripts

  • Run pre and post script

  • Control application version

  • Edit package JSON

  • Automatically set up and open your github Library

  • Custom npm init script

  • Submit your first Commit to GitHub using a custom npm init script

1. Learn basic shortcuts

Let's start with the basics. Learning the most common npm shortcuts will save a lot of time in the long run.

  • Installation -   general: npm install, short: npm i.

  • Test   -   general: npm test, short: npm t.

  • Help - General: npm --help, short: npm -h.

  • Global flag - General: --global, short form: -g.

  • Save as development dependency - General: - save dev, short form: -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 the package, but now this is the default value. To install a package without saving it, use the -- no save flag.

Less common shortcut keys

There are also some uncommon shortcuts, as follows:

  • The installation package information will be added to optionaldependences (optional phase dependency) - General: --save-optional, short form: -O.

  • Precise installation of the specified module version - General: --save optional, short form: -O.

If you need to save an npm package locally or select a group of available packages through a single file download, you can use --save bundle or -B to bundle them together and use npm pack to obtain the bundle.

Shortcut to root

The symbol is usually used to represent the root directory of an application. In npm terms, the entry point of an application, that is, package The value specified as "main" in JSON

{  "main": "index.js"}

This shortcut can also be used for things like NPX create react app Such commands. Therefore, you can run NPX create react app, Instead of using NPX create react app my app to create a new my app directory.

2. Set default npm init attribute

When you run npm init to start a new project, you may find yourself entering configuration details again and again. If so, you may be the main person in charge of the project. Sometimes, to save time, you can set default values for these fields, as follows:

npm config set init.author.name "Joe Bloggs"npm config set init.author.email "JoebLoggs@gmail.com"npm config set init.author.url "Joebloggs.com"npm config set init.license "MIT"

To check whether these attributes are added correctly, enter npm config edit on the terminal to view the configuration file information. Of course, you can also edit the information directly in the open configuration file. If you want to edit the 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 refills the configuration file with default settings.

echo "" > $(npm config get userconfig)npm config edit

The above script will reset the user defaults, and the following script will reset 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. If you only deal with specific projects, this is not a problem, but in many cases, cross platform compatibility is necessary: any open source or collaborative projects, 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 best one is cross env. Use NPM I -d cross env to install it as a development dependency. 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 achieve cross platform compatibility:

  • rimraf can be installed to run cross platform scripts worldwide

  • ShellJS is a Unix shell command on node Portable implementation on JS API.

4. Running 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.

First, install the development dependency through NPM I -d concurrent. Then add it to the script in the following format:

{  "start": "concurrently \"command1 arg\" \"command2 arg\""}

5. Run scripts in different directories

Sometimes, you have a folder that contains multiple packages JSON file. It is convenient to access these scripts from the root directory 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 ..

However, there is a more elegant solution, that is, use the --prefix flag to specify the path:

npm start --prefix path/to/your/folder

The following 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 on 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

Usually, during the development of a full stack application, we may want to start the server and client at the same time. The wait on node module provides a convenient way to ensure that processes only occur when certain processes are ready: in our example, we have a specific port.

For example, this is the dev script I used in the Electron project using the react front end. When used at the same time, the script loads the presentation layer and the Electron window in parallel. However, using wait on, you can only http://localhost:3000 The Electron window will not open until it is started.

"dev": "concurrently \"cross-env BROWSER=none npm run start\" \"wait-on http://localhost:3000 && electron .\"",

In addition, react will open 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 available scripts

List package The scripts available in the JSON file are simple: just go to the root directory of the project and enter npm run in the terminal.

However, there is a more convenient way to get the script list, which can be 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 select one to run.

8. Run pre and post script

You may be familiar with scripts such as prebuild and postbuild, which allow you to define the code to run before or after building the 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 application version

npm provides some useful shortcuts to accomplish this, as opposed to manually changing the version of an application. To increase the version, add major, minor or patch`when running npm version:

// 1.0.0npm version patch// 1.0.1npm version minor// 1.1.0npm version major// 2.0.0

Depending on how often the application is updated, you can save time by increasing the version number at each deployment, using the following script:

{  "predeploy": "npm version patch"}

10. Edit package JSON

Package json is a regular json file, so you can edit it from the command line using the tool library json. This is when modifying the package json provides another new way to allow w you q to create shortcuts that exceed the default values. Global installation:

npm install -g json

You can then use it to use -I for in place editing. For example, to add a new script "foo" with a value of "bar", write:

json -I -f package.json -e 'this.scripts.foo="bar"'

11. Automatically set up and open your github Library

If package If there is "repository" in the JSON file, you can open it in the default browser by entering npm repo.

If your project is connected to a remote repository and git is installed on the command line, you can use this command to find your connected repository.

git config --get remote.origin.url

Even better, if you follow the above prompts and install the json module, you can use the following script to automatically add the correct repository to the package json

json -I -f package.json -e "this.repository=\"$(git config --get remote.origin.url)\""

12. Custom npm init script

Let's go a step further and use our own npm init script, which accepts the GitHub repository URL and automatically pushes our first submission. In this tip, we will discuss how to create a custom npm init script. In the next (and final) tip, we will merge git.

You can redirect to the in your home directory npm init JS file to edit the npm init script. (on Windows, it is usually c/users/< user name >, on Mac, it is /users/< user name >).

Let's first create one in our home directory NMM init JS file. To ensure that npm init is pointing to the correct file, run:

npm config set init-module ~\.npm-init.js

Before integrating git, here is a simple npm init JS file, which simulates the problem 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 <joe.bloggs@gmail.com> (joebloggs.com)'),  license: prompt('license', 'ISC')}

Each problem follows the nameInPackage pattern: prompt('nameInPrompt','defaultValue'). To set the value without problems by default, simply remove the prompt method.

To return to the default settings, simply delete NPM init JS.

13. Submit your first Commit to GitHub using a custom npm init script

To merge git commands into NPM init JS file, you need a way to control the command line. To do this, we can use child_process module. It is introduced at the top of the file. Because we only need the execSync function, we can use the destruct assignment syntax to obtain it ourselves:

const { execSync } = require('child_process');

I also created a helper function that prints the results of the function to the console:

function run(func) {  console.log(execSync(func).toString())}

Finally, we will prompt for the GitHub repository URL. If so, we will generate readme MD file and start 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 NPM init JS file is as follows:

const { execSync } = require('child_process');
function run(func) {  console.log(execSync(func).toString())}
module.exports = {  name: prompt('package name', basename || package.name),  version: prompt('version', '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 <joe.bloggs@gmail.com> (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 <joe.bloggs@gmail.com> (joebloggs.com)",  "license": "ISC",  "repository": {    "type": "git",    "url": "git+https://github.com/JoeBloggs/custom.git"  },  "bugs": {    "url": "https://github.com/JoeBloggs/custom/issues"  },  "homepage": "https://github.com/JoeBloggs/custom#readme"}

You can also further achieve this by merging GitHub API s, so that you do not need to create a new repository. This part is left to you.

In general, I hope this article can let you know what npm can achieve and show you some ways to improve work efficiency - whether you know common shortcuts or by making full use of script package JSON, or write a custom version of npm init.


  • Welcome to join our wechat (winty230) to bring you into the technology group for long-term exchange and learning

  • Welcome to pay attention to "front-end Q", learn from the front-end seriously, and be a professional technician

Click to support me

Tags: Linux Java Python git Vue

Posted by 01706 on Mon, 30 May 2022 09:16:39 +0530