IO/nPM-tips-an… bitsrc. IO/nPM-tips-an… “, with the understanding of the bottle king, slightly changed from the original

NPM, Node Package Manager, is a Package Manager for the JavaScript programming language. Any developer who uses Javascript has used this excellent CLI tool to install dependencies for their projects.

In this article, I will share NPM tips and tricks that can increase your productivity and make you use NPM smarter and more efficiently.

1. Initialize the package

We can run the NPM init command to initialize the package, but it will ask for information about the package, author, and so on. There is another way to automatically generate our package.json using the NPM init-y command.

npm init -y
Copy the code

We can also use the NPM config command to set some default initialization configurations, such as author details.

npm config set init-author-name "Ankit Jain"
npm config set init-author-email "[email protected]"
Copy the code

Then run NPM init -y to automatically generate our package:

{
  "name": "<name of the root dir>"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": "Ankit Jain <[email protected]>"."license": "ISC"
}
Copy the code

We can also extend the functionality of NPM init by configuring our own javascript files using NPM config:

npm config set init-module <path-of-the-custom-file>
Copy the code

2. Install packages from different sources

The NPM CLI also allows you to install javascript packages from other sources (such as Bit, tarball files, GitHub, Bitbucket, and GIST).

# Install a component from Bit (set Bit as a scoped registry)
npm config set @bit:registry https://node.bit.dev
npm i @bit/username.collection.component
# Install from tarball stored locally
npm i ./local-tarball-package.tgz
# Install tarball package from internet
npm i https://abc/xyz/package.tar.gz
# Install from github repo
npm i githubuser/reponame
# Install from bitbucket repo
npm i bitbucket:bitbucketuser/reponame
# Install from gist
npm i gist:gistID
Copy the code

For example, install the button component from Bit

Suppose I need a button component, and one of my teammates has a button component published to our component collection on Bit.

First, configure the Bit as scope.

npm config set @bit:registry https://node.bit.dev
Copy the code

Then, I’ll go to my team’s component set and look for buttons:

Locate the Button component, copy the install command, and install using NPM

npm i @bit/the_a-team.imperfect-components.button
Copy the code

Name of my Team: “The A-Team”. Our component set name: “Imperfect Components”.

For example, install the Icon component from the NPM enterprise repository

For example, I need to install an Icon component in my project, and one of my teammates has published the button component on the NPM enterprise repository.

We can also use scope to associate with corporate private repositories. This allows you to use modules in both the NPM public repository and some other private repository:

npm config set @xscope:registry https://xxx.com/npm/
Copy the code

Multi-source installation: no user awareness

Each time the user uses the private library, the user needs to switch the NPM image path, use the hooks of NPM preinstall, and add scripts to the project package.json so that the partner can install without knowing:

// NPM preinstall hook "scripts": {"preinstall": "node./bin/preinstall.js"}Copy the code

Configuration. / bin/preinstall. Js:

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

exec('npm config get registry'.function(error, stdout, stderr) {
  if(! stdout.toString().match(/registry\.x\.com/)) {
    exec(' npm config set @xscope:registry https://xxx.com/npm/'); }});Copy the code

3. Install a new dependency package

We can run NPM CI to completely install our software dependencies. It is commonly used in automation environments such as CI/CD platforms.

npm ci
Copy the code

It differs from NPM Install in the following respects:

  • It will be based onpackage-lock.jsonInstalling dependencies ensures that the entire development team is using the same version of dependencies and avoids wasting time troubleshooting strange problems caused by inconsistent dependencies
  • It will be installedpackage-lock.jsonThe exact version of the package mentioned in the file can greatly speed up node module installation in most cases without calculating the dependency satisfaction problem
  • It first deletes the existing ones in the projectnode_modulesAnd then install it all new
  • It won’t saypackage.jsonOr any lock: The installation is basically frozen
  • npm installYou can install a single dependency packagenpm ciYou can only install all project dependencies at once, not individual dependencies

In addition, if package-lock.json is obsolete (conflicting with package.json), the NPM CI will be nice enough to report an error, preventing project dependencies from becoming obsolete.

Note: If you use NPM CI, don’t forget to add package-lock.json to your Git repository.

4. Use a shortcut to install the package

This is the most useful feature and can be used to save time when installing packages:

# Install package
npm install <package_name>
Shortcut: npm i <package_name>
# Install devDependencies
npm install --save-dev <package_name>
Shortcut: npm i -D <package_name>
# Install dependencies (This is default)
npm install --save-prod <package_name>
Shortcut: npm i -P <package_name>
# Install packages globally
npm install --global <package_name>
Shortcut: npm i -g <package_name>
Copy the code

Install multiple packages in a single command:

npm i express cheerio axios
Copy the code

Install multiple packages with the same prefix:

npm i eslint-{plugin-import,plugin-react,loader} express
Copy the code

5. NPM scripts

NPM Scripts is the most useful feature. In addition to predefined before and after hooks (commonly referred to as lifecycle scripts), it also supports custom scripts, such as:

  • preinstall: It runs before installing any dependency packages

We can also run the NPM run env in the project to list all the NPM environment variables that exist in the project. Includes package attributes prefixed with npM_package_.

npm run env
Copy the code

Output:

npm_config_save_dev= npm_config_legacy_bundling= npm_config_dry_run= npm_config_viewer=man . . npm_package_license=ISC #  Package properties npm_package_author_name=Ankit Jain npm_package_name=npm-tips-and-tricks # Name of our package . .Copy the code

We can also access the above env variables in our code via process.env.npm_package_name and other similar variables.

Configure your own variables in package.json

We can define config in package.json to define our own variables as NPM environment variables prefixed with nPM_package_config_ as follows:

"config": {
    "myvariable": "Hello World"
},
Copy the code

Now, let’s check in the env variable:

npm run env | grep npm_package_config_
Copy the code

Output:

npm_package_config_myvariable=Hello World
Copy the code

Define our custom script

The NPM run command displays all the scripts we defined in the package.json file.

Let’s add some custom scripts to package.json:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js",
    "echo-hello": "echo \"Hello\"",
    "echo-helloworld": "echo \"Helloworld\"",
    "echo-both": "npm run echo-hello && npm run echo-helloworld",
    "echo-both-in-parallel": "npm run echo-hello & npm run echo-helloworld",
    "echo-packagename": "echo $npm_package_name",
    "echo-myvariable": "echo $npm_package_config_myvariable",
    "echo-passargument": "npm run echo-packagename -- \"hello\"",
    "echo-pipedata": "cat ./package.json | jq .name > package-name.txt"
},
Copy the code

Run the following command:

npm run
Copy the code

Output:

# npm-tips-and-tricks (name of our package)
Lifecycle scripts included in npm-tips-and-tricks:
  test
    echo "Error: no test specified" && exit 1
  start
    node index.js
available via `npm run-script`:
  echo-hello
    echo "Hello"
  echo-helloworld
    echo "Helloworld"
  echo-both
    npm run echo-hello && npm run echo-helloworld
  echo-both-in-parallel
    npm run echo-hello & npm run echo-helloworld
  echo-packagename
    echo $npm_package_name
  echo-myvariable
    echo $npm_package_config_myvariable
  echo-passargument
    npm run echo-packagename -- "hello"
  echo-pipedata
    cat ./package.json | jq .name > package-name.txt
Copy the code
Run a simple NPM script:
npm run echo-hello
# Output
> echo "Hello"
Hello
Copy the code
Run multiple scripts in a single NPM script:

We can run multiple scripts using &&. Both scripts run consecutively, that is, one after the other.

npm run echo-both
# Output
> npm run echo-hello && npm run echo-helloworld
> [email protected] echo-hello 
> echo "Hello"
Hello
> [email protected] echo-helloworld
> echo "Helloworld"
Helloworld
Copy the code

We can also run multiple scripts in parallel using &.

npm run echo-both-in-parallel
# Output
> npm run echo-hello & npm run echo-helloworld
> [email protected] echo-hello
> echo "Hello"
> [email protected] echo-helloworld
> echo "Helloworld"
Hello
Helloworld
Copy the code
Use NPM environment variables in NPM scripts
npm run echo-packagename
# Output
> echo $npm_package_name
npm-tips-and-tricks
-------------
npm run echo-myvariable
# Output
> echo $npm_package_config_myvariable
Hello World
Copy the code
Pass the parameters to another NPM script

We can use — to pass parameters to the NPM script. In the example below, we pass Hello as an argument to the Echo-Packagename script.

npm run echo-passargument
# Output
> npm run echo-packagename -- "hello"
> [email protected] echo-packagename
> echo $npm_package_name "hello"
npm-tips-and-tricks hello
Copy the code
Use pipes to pass data from one NPM script to another
npm run echo-pipedata
# Output
> cat ./package.json | jq .name > package-name.txt
# Let's cat package-name.txt
cat package-name.txt
# Output
"npm-tips-and-tricks"
Copy the code

6. Quickly navigate to a packaged document

We can quickly navigate to the documentation of any NPM package by simply running the following command:

npm docs <package-name>
OR
npm home <package-name>
Copy the code

If we want to check for any unresolved issues or file any bugs into the NPM package, we can also navigate to the site by running the following command:

npm bug <package-name>
Copy the code

Similarly, NPM repo opens the GitHub repo page in a browser.

7. Delete the duplicate packages

We can remove duplicate dependencies by running the NPM dedupe command. It simplifies the overall structure by removing duplicate packages and effectively sharing common dependencies among multiple dependent packages. This creates a flat, deduplication-enabled tree.

npm dedupe or npm ddp
Copy the code

8. Scan your application for vulnerabilities

We can run the NPM audit command to scan for any vulnerabilities in any dependencies in our project. It generates and displays beautiful output in a tabular format (we can also get the output using JSON), and if other packages are multilevel/multi-dependent, then all other packages depend on this package.

NPM Audit Fix automatically installs patched versions of all bug packs (if available)

npm audit fix
Copy the code

9. Check the environment

We can use the NPM doctor command to run multiple checks in our environment, such as whether our NPM CLI has sufficient permissions to install javascript packages and whether it can connect to the NPM registry. It also checks the Node and NPM versions to verify the cache for corrupted packages.

npm doctor
Copy the code

10. Test your package locally

NPM provides the NPM link command so that we can work and test packages iteratively. NPM Link creates a symbolic link to our test package in the global NPM Modules folder. We can install this package into our test application by running NPM link . This will create a symbolic link from the globally installed package to our project node_modules directory. It is useful when testing local packages or working with local NPM packages.

cd /test-package (package name is helloworld)
npm link                     # Global symlink created
cd /application
npm link helloworld         # Create symlink in node_modules 
Copy the code

11. Check whether the package is out of date

We can use the NPM outdated command to check all outdated NPM packages. It also shows the latest version that should be installed for outdated packages.

npm outdated --long or npm outdated -l
Copy the code

We can also check the latest version of any NPM package by simply running the following command:

# Shows the package information
npm view <package-name> or npm v <package-name>
# Shows the latest version only
npm v <package-name> version
# Shows the list of all versions
npm v <package-name> versions
Copy the code

12. List all installed software packages

By running the NPM list command, we can list all the NPM packages installed in the project. It creates a tree structure showing installed packages and their dependencies.

npm list or npm ls 
Copy the code

We can use the -depth flag to limit the depth of the search:

npm ls --depth=1
Copy the code

conclusion

In this article, we’ve learned some useful NPM tips and tricks that you can use to increase your development efficiency. Feel free to post more NPM tips in the comments section.

Thank you for reading

Welcome to pay attention to “front-end bottle Gentleman”, reply to “communication” to join the front-end communication group!

Welcome to pay attention to “front-end bottle gentleman”, reply to “algorithm” automatically join, from 0 to 1 to build a complete data structure and algorithm system!

Here, I not only introduce algorithms, but also combine algorithms with various front-end areas, including browsers, HTTP, V8, React, Vue source code, and so on.

Here (algorithm group), you can learn a dachang algorithm programming problem (Ali, Tencent, Baidu, Byte, etc.) or Leetcode every day, Mr. Aquarius will solve it the next day!

In addition, there are handwritten source code problems every week, Aquarius will also solve!