27
头图
Constraints through documentation and communication are far inferior to constraints through tools (code).

development environment

  1. Node.js
  2. Package Manager (npm, yarn, pnpm)

Pain point problem

The Node.js versions of member machines are not uniform: 12.x for the old school, 14.x for the conservative, and 17.x for the radical. Whether the project can run normally depends on God's will, and the online risks can be imagined in the scenario where there is no CICD pipeline to support the local npm run build.

Some people are used to using npm, some people are used to using yarn, and there are often cases where package-lock.json and yarn.lock files exist at the same time in the code base. The more painful point is that there are no clues to troubleshoot all kinds of strange problems.

All we have to do is strangle the problem at the source: lock down the Node.js version and package manager

Lock the project Node version

By specifying the engines field in package.json, you can qualify the node version used by your project. The following configuration only allows users to use version 14 or 16. For more configuration, please refer to package.json | npm Docs , semver

 // package.json 
  "engines": {
    "node": "14.x || 16.x"
  },

After configuration, you will find that this field is only valid for yarn. So how does it work for npm?
Add the following configuration to the .npmrc file in the project root directory

 // .npmrc
engine-strict = true

After the above configuration is complete, try npm install, the wrong Node.js will exit directly

Lock down the package manager

Quickly achieve locking with only-allow toolkits, npm scripts .

Step 1: In the project npm install -D only-allow

Step 2: Configure in the package.json file scripts.preinstall , the allowed input values only-allow npm, only-allow pnpm, only-allow yarn

 // package.json
"scripts": {
    "preinstall": "npx only-allow npm",
    ...
}

After the above configuration is completed, you can use it again (yarn, npm, pnpm)


亖混子
4.7k 声望2.4k 粉丝

自信、自洽、自在