My name is Shanyue and this is my thirteenth article on Node progression. Welcome to my blog: shfshanyue/blog and the Node Progression series

As we all know, a scripting class tool for a javascript project can be organized using the scripts field in package.json, which is simply called NPM Script.

The most typical and common convention is NPM start, which is used to start a project:

{
  "scripts": {
    "start": "next"}}Copy the code

There are many more conventions, listed below

  • npm install
  • npm test
  • npm publish
  • .

If you need to execute it, use the NPM prefix, such as NPM start. What about other scripts? That requires the NPM run prefix. Yarn doesn’t have the same level of care.

$ npm run <user defined>
$ npm run-script dev

# for the sake of simplicity, is equivalent to
$ npm run dev

# yarn 
$ yarn dev
Copy the code

The above is well known, and the following lecture may not be well known

Run: NPM run dev vs. NPM start

For a front-end project that generates purely static page packaging, there is little difference: the deployment of the production environment depends only on the resources generated by the build, much less on NPM scripts. See how to deploy the front-end project.

A project generated using create-react-app has only NPM start in its NPM script

{
  "start": "react-scripts start"."build": "react-scripts build"."test": "react-scripts test"."eject": "react-scripts eject"
}
Copy the code

The project generated using Vuepress has only NPM run Dev in its NPM script

{
  "dev": "vuepress dev"."build": "vuepress build"
}
Copy the code

In a service-oriented project like Next, Nuxt, and Nest. Dev and start tend to be distinct, one for production and one for development

  • Dev: Start a project in a development environment, usually with the watch option to listen for file changes and restart the service. This will consume a lot of CPU performance and is not suitable for production environment
  • Start: Starts the project in production

Configure in the Nest project

{
  "start": "nest start"."dev": "nest start --watch"
}
Copy the code

How to get new projects running fast

It’s a problem everyone has when they come into a beginner’s program, and how to make it work: everyone starts out as a beginner.

You might blurt out: NPM run dev/ NPM start, but in practice it’s not that simple.

  1. Check if there areCI/CDIf there is a followCI/CDDeployed scripts run commands
  2. Check if there aredockerfileIf there is a followdockerfileRun the command
  3. Check NPM scripts for dev/start and trynpm run dev/npm start
  4. Check to see if there is documentation, and if there is, follow the documentation. Why put the document last? You know why

But even if you’re being cautious, you’re likely to run into some of the most annoying ones that could waste an afternoon:

  1. The front-end may need to rely on the files generated during the front-end build to start the local environment, so sometimes you need to deploy it properly and then try to start it according to the local environment (that is, NPM run build and then NPM run dev/ NPM start). (For example, one time our project NPM Run Dev needed the webPack DllPlugin built)
  2. Don’t forget to set environment variables or configuration files

Therefore, having a small script is a good way to prevent future generations from stepping on you and, more importantly, from scolding you

{
  "scripts": {
    "start": "npm run dev"."config": "node assets && node config"."build": "webpack".// Set a dev hook before NPM run dev, which may not be required
    "predev": "npm run build"."dev": "webpack-dev-server --inline --progress"}}Copy the code

Hooks

In NPM Script, there are Pre/Post hooks for each command, which are executed before and after the command is executed

npm run <script>
pre<script>
<script>
post<script>
Copy the code

At work, these hooks and built-in commands provide an easy way to operate a project and a more secure project flow

  1. After the package is loaded, husky(V5.0) is set up
  2. Before packing, clean up the target file
  3. Before you ship the package, build the package
  4. Before running, prepare the resource files
{
  "scripts": {
    "postinstall": "husky install"."prebuild": "rimraf dist"."build": "webpack"."predev": "npm run assets"."dev": "webpack-dev-server --inline --progress"}}Copy the code

build

Build package, which is included in almost all projects and defaults to NPM run build.

In CI or the front-end hosting platform Vercel/Netlify, the most important step for deploying a front-end project is packaging. However, some projects may not need to be packaged, in which case you can use the if-present parameter, indicating that if the script exists, then execute, otherwise skip


$ npm run --if-present build
Copy the code
{
  "scripts": {
    "build": "next build"}}Copy the code

Test: Script suffix

For doing something extremely complex, NPM scripts can be grouped using prefixes, such as tests.

  • npm run testUse:mochaUnit testing
  • npm run test:coverageUse:nycView unit test coverage
  • npm run test:e2eUse:cypressPerform automated UI testing
{
  "test": "mocha"."test:coverage": "nyc npm test"."test:e2e": "npm run cy:run --"."cy:run": "cypress run --config-file cypress/config.json"."cy:open": "cypress open --config-file cypress/config.json"
}
Copy the code

For testing, Mocha works well with NYC for unit testing and coverage reporting.

Cypress and Puppeteer are undoubtedly the most popular frameworks for front-end E2E testing.

How to better test and document the Vue/React component?

Component testing:

Storybook makes it easier to debug, test, and document React/Vue components. When developing the base component library, you can configure NPM Run Storybook for better testing

$ npm run storybook
Copy the code
{
  "scripts": {
    "storybook": "start-storybook -p 9001 -c .storybook"."storybook:build": "build-storybook -c .storybook -o .out"."prepublishOnly": "npm run build"}}Copy the code

Formatting: Prettier

Prettier is a code formatting tool that supports HTML, CSS, js, graphql, markdown, etc., and can be deeply integrated with an editor (vscode).

Configure code formatting in NPM Script as follows: format JS, CSS, JSON, markdown

{
  "scripts": {
    // Configuration file:.prettierrc
    // Format: --write
    // File: *.js
    "prettier": "prettier --config .prettierrc --write {.,components,lib,pages}/*.{js,css,json,md}",}}Copy the code

. Prettierrc is the configuration file for prettier, where there are few prettier Options.

{
  "singleQuote": true."printWidth": 100."semi": false."arrowParens": "avoid"
}
Copy the code

Lint: Code formatting and quality checking

What’s the difference between Prettier and ESLint/StyleLint/TSLint?

Prettier simply formats code, such as Spaces, whether to add semicolons, and so on. In addition to formatting code, rules such as no-unused-vars and no-implicit-globals are also used to check code quality.

JS and TS quality check, still depends on ESLint.

{
  "scripts": {
    "lint": "eslint ."."lint:fix": "eslint . --fix"}}Copy the code

In addition to ESLint, markDown and gitCOMMIT can also be formatted

  • markdownlint
  • commitlint

Git: Hello, this code is not acceptable. Submission is prohibited here

Your code is not up to standard, in order to prevent you from being teased by others, submission is not allowed here. This is where Git Hooks come in.

Precommit Hook in Git Hooks executes the script before committing, and disallows commit if the script does not pass (Exit Code is not 0).

Husky and Lint-staged are best suited to Git Hooks.

{
  "scripts": {
    "lint": "eslint ."."prettier": "prettier --config .prettierrc --write {.,components,lib,pages}/*.{js,css,json,md}",},"husky": {
    "hooks": {
      "pre-commit": "lint-staged"}},"lint-staged": {
    "*.js": [
      "npm run lint"]."*.{js,css,json,md}": [
      "npm run prettier"]}}Copy the code

This style is Outdated: Your dependence has expired

What happens when a library expires?

  • Can’t find the files, nowhere to go
  • There are often bugs caused by out-of-date libraries that are difficult to fix
  • Security risks exist

No one likes an out-of-date library.

Use NPM outdated to discover outdated libraries that are dependent on in package.json

$NPM outdated Package Current Wanted Latest Location 收 入 来 @vuepress/ plugin-Google -analytics 1.7.1 1.8.2 1.8.2 Node_modules /@vuepress/ plugin-Google - Analytics blog axios 0.21.0 0.21.1 0.21.1 node_modules/axios blog dayjs 1.9.6 Dayjs blog GraphQL 15.4.0 15.5.0 15.5.0 Node_modules/DayJS blog KOa 2.13.0 2.13.1 2.13.1 Node_modules/KOa blog npm-check-updates 10.2.2 10.3.1 11.3.0 node_modules/npm-check-updates blog vuepress 1.7.1 1.8.2 1.8.2 node_modules/vuepress blogCopy the code

But NPM Outdated is not very useful, like how do you upgrade with one click? Just like the app store updates all mobile apps.

Node-check-updates is an upgraded VERSION of NPM Outdated. The simplest function of this version is one-click upgrade, and the refinement function is upgrade policy and security upgrade. Ncu is its binary command

$ncu Checking package. Json [= = = = = = = = = = = = = = = = = = = =] 5/5 100% express 4.12 x to 4.13 x multer ^ 0.1.8 - ^ 1.0.1 React-bootstrap ^0.22.6 → ^0.24.0 react-a11y ^0.1.1 → ^0.2.6 webpack ~1.9.10 → ~1.10.5 Run nCU-u to upgrade package.jsonCopy the code

With nCU –doctor, the project is tested as each dependency is upgraded, and if the test passes, the dependency is installed successfully, otherwise it falls back to the previous version

$ ncu --doctor -u
npm install
npm run test
ncu -u
npm install
npm run test
Failing tests found:
/projects/myproject/test.js:13
  throw new Error('Test failed! ')
  ^
Now let's identify the culprit, shall we? Restoring package.json Restoring package-lock.json NPM install NPM install --no-save [email protected] NPM run test ✓ react 15.0.0 → 15.0.0 NPM install --no-save [email protected] NPM run test Can go onto those who qualify react-redux upgraded package.jsonCopy the code

Configure nCU in NPM script:

{
  "scripts": {
    "ncu": "ncu"}}Copy the code

Audit: Your dependency is a security risk

When a package poses a security risk, this is the time to be careful, after all, you don’t want your site to be attacked. The only solution is to upgrade the package. Like Github’s bot:

Is there a security risk in using NCU to update all dependencies to the latest?

Yes, because NCU only updates dependencies in package.json to the latest, not dependencies in lock file.

NPM Audit can discover risk libraries in a project and fix them using NPM Audit Fix.

However, the accuracy of NPM audit is not as high as yarn Audit.

In addition, YARN Audit does not support automatic repair of YARN Audit Fix

$ npm audit

$ npm audit fix
Copy the code

Snyk is a package risk checking service that provides a command-line tool for risk detection that can be used instead of NPM Audit. It also has the disadvantage of relying on a service, which can be built on a container or use SASS.

{
  "scripts": {
    "audit": "snyk test"."audit:fix": "snyk protect"}}Copy the code

Size: Controls the Size of your bundle

Size limit and Bundle size are two tools that can control the size of bundles, but size limit also has stronger support for startup times.

{
  "scripts": {
    "size": "size-limit"."analyze": "size-limit --why"
  },
  "size-limit": [{"path": "dist/promise-utils.cjs.production.min.js"."limit": "10 KB"
    },
    {
      "path": "dist/promise-utils.esm.js"."limit": "10 KB"}}]Copy the code

conclusion

Efficient use of NPM Script in work can achieve high efficiency and code quality. The package involved in this paper is shown below

  • husky
  • mocha
  • nyc
  • cypress
  • puppeteer
  • storybook
  • prettier
  • eslint
  • markdownlint
  • @commitlint/cli
  • lint-staged
  • husky
  • npm-check-updates
  • lerna
  • size-limit
  • bundle-size

You can find more interesting and useful libraries in NPM devtool