Let me tell you something about the invincible NPM packages

Time:2021-10-22

In the face of busy schedule and urgent construction period constraints, it is undoubtedly important to choose tools that can effectively improve productivity.

Here, I sort out a list of my favorite NPM packages. In order to facilitate browsing, I also classified them, hoping to present a clearer structure.

Of course, you don’t have to install and learn all of them. In most cases, selecting one for each category is sufficient to meet production needs. I just want to provide more alternatives to help each reader find the most suitable option. Don’t gossip. Let’s start right away!

Utilities

Lodash

lodashIs a modern JavaScript utility library that provides modularity, performance and a variety of additional functions. It can provide a variety of practical functions about JavaScript arrays, objects and other data structures.

Let me tell you something about the invincible NPM packages

Installation and examples

yarn add lodash

Don’t abuse, try to use ES’s own method。 Some of my common methods are as follows

//---------------------------------- depth comparison whether the values of two objects are all equal
import { isEqual, cloneDeep, uniqBy, sortBy } from "lodash";

const object = { a: 1 };
const other = { a: 1 };

isEqual(object, other);
// => true

object === other;
// => false

//------------------------- deep copy
const objects = [{ a: 1 }, { b: 2 }];

const deep = cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

//------------------------- array de duplication
uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], "x");
// => [{ 'x': 1 }, { 'x': 2 }]

//------------------------- array sorting
const users = [
  { user: "fred", age: 48 },
  { user: "barney", age: 36 },
  { user: "fred", age: 40 },
  { user: "barney", age: 34 },
];
sortBy(users, "age");
/*
[
  { 'user': 'barney', 'age': 34 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred', 'age': 40 },
  { 'user': 'fred', 'age': 48 },
];
*/

qs

qsHandle URL query strings and support embedded objects and arrays. In short, it is to convert the parameters of the object and the URL address to each other

Let me tell you something about the invincible NPM packages

Installation and examples
yarn add qs
import { parse, stringify } from "qs";

//Use I
//Convert URL address parameters on the browser to objects (string to object)
const urlParams = parse(window.location.href.split("?")[1]);

//Use II
//Pass the object parameters to the back-end interface -- get request (object to string)
const params = {
  name: "wang",
  age: "18",
  Sex: "female",
};

// =>  /api/user?name=wang&age=18&sex=%E5%A5%B3
const apiUrl = `/api/user?${stringify(params)}`;

classnames

classnamesConditionally group class names together

Installation and examples

yarn add classnames

Error ❎ Code example: when multiple style class names are dynamically added to react native, an error will be reported:

import styles from "./index.less";

const Index=()=><div className={style.class1 style.class2}</div>

It can be solved by modifying to the following code

import React from "react"
import classnames from 'classnames'

import styles from "./index.less";

const Index=()=>(<div
          className=classnames({
              style.class1,
              style.class2
          })>
</div>)

numeral

numeralIt is an NPM library specially used to format numbers. At the same time, numerical can analyze numbers in various formats.

Let me tell you something about the invincible NPM packages

Installation and examples

yarn add numeral
import numeral from "numeral";

//Analytic number
numeral("10,000.12"); // 10000.12
numeral("$10,000.00"); // 10000
numeral("3.467TB"); // 3467000000000
numeral("-76%"); // -0.76

//Format

numeral(10000.23).format("0,0"); // '10,000'
numeral(1000.234).format("$0,0.00"); // '$1,000.23'

cross-env

cross-envIs a runCross platformScripts for setting and using environment variables

Installation and examples
yarn add cross-env --dev
  "scripts": {
    "start": "cross-env REACT_APP_ENV=development webpack",
    "build": "cross-env REACT_APP_ENV=production webpack",
  },

path-to-regexp

path-to-regexpIt is used to process the address and parameters in the URL, which can easily get the data we want.

JSRegExpMethod to do regular expression verification, andpath-to-regexpIt can be regarded as a regular expression of URL string.

Installation and examples

yarn add path-to-regexp

pathToRegexpMethods can be compared to JSnew RegExp('xxx')

import pathToRegexp from "path-to-regexp";

const re = pathToRegexp("/foo/:bar");
console.log(re); // /^\/foo\/((?:[^\/]+?))(?:\/(?=$))?$/i

compileParameter value used to populate the URL string.

var pathToRegexp = require("path-to-regexp");

var url = "/user/:id/:name";
var data = { id: 10001, name: "bob" };

// /user/10001/bob
console.log(pathToRegexp.compile(url)(data));

Date format

Day.js

Day.jsIt is fast and lightweightMoment.js(enter the pure maintenance mode since September 2020, and no new version will be developed) alternative scheme. Both have similar APIs, as long as you have access to themMoment.js, you can get started quicklyDay.js

Let me tell you something about the invincible NPM packages

install

yarn add dayjs

Example

import dayjs from "dayjs";

const myformat = "YYYY-MM-DD HH:mm:ss";

//----------------- returns the current time as a string
const data = dayjs().format(myformat);
// =>  2020-11-25 12:25:56

//----------------- date formatting
const data1 = dayjs("2020-11-25 12:25:56").format("YYYY/MM/DD HH/mm/ss");
// => 2020/11/25 12/25/56

//How long ago
var relativeTime = require("dayjs/plugin/relativeTime");
dayjs.extend(relativeTime);
const data1 = dayjs("2020-11-25 11:40:41").fromNow();

// =>

Linters and formatting tools

ESLint

ESLintIs a useful tool to avoid code errors and force development teams to use coding standards. Eslint is a tool for identifying and reporting patterns in ECMAScript / JavaScript code. Eslint has comprehensive pluggable features. Each rule corresponds to a plug-in for you to add more content at runtime.

Let me tell you something about the invincible NPM packages

Installation and use
$ yarn add eslint --dev

Then you should set up a profile:

$ ./node_modules/.bin/eslint --init

After that, you can run eslint on any file or directory as follows:

$ ./node_modules/.bin/eslint yourfile.js

For more instructions, seeOfficial documents, there are many getting started and configuration examples.

Prettier

PrettierIs a distinctive style of code formatter. It realizes a unified style by parsing the code and re outputting the code with its own rules (limiting the maximum length);

Let me tell you something about the invincible NPM packages

install

yarn add --dev --exact prettier

Example

establish.prettierrc.jsAdd custom formatting rules

module.exports = {
  trailingComma: "es5",
  tabWidth: 4,
  semi: false,
  singleQuote: true,
};

establish.prettierignoreAdd files or directories that need to be ignored

# Ignore artifacts:
build
coverage

Execute format command

#Format all JS files in the SRC directory

prettier --write "src/**/*.js"

stylelint

stylelintA powerful style rule allows you to enforce style specifications and avoid writing wrong style code

install

yarn add stylelint stylelint-config-standard --dev

Example

establish.stylelintrc.jsAnd add configuration

module.exports = {
  extends: "stylelint-config-standard",
};

Execute the lint command

#Check whether all CSS files in SRC directory comply with the specification
npx stylelint "src/**/*.css"

Husky 

HuskyIt can help us implement git hooks simply and directly. Your team is working on collaborative development and hopes to implement a set of coding standards in the whole team? no problem! With husky, you can ask everyone to automatically complete lint and test their code before submitting or pushing to the repository.

Let me tell you something about the invincible NPM packages

Installation and examples
yarn add husky --dev

The following is an example of implementing husky hooks:

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "npm lint",
      "pre-push": "npm test"
    }
  }
}

herepre-commitofhooksWill run before you commit to the repository. Before pushing the code to the repository, thepre-push hook


‍ ♂️ Data generator

Uuid

uuidIs a convenient micro software package, which can quickly generate more complex universal unique identifier (UUID).

Installation and examples

npm install uuid
import { v4 as uuidv4 } from "uuid";
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

faker.js

faker.jsA very practical toolkit for generating a large amount of false data in the browser and node.js.

Let me tell you something about the invincible NPM packages

Installation and examples

yarn add faker
import faker from "faker"

function generateCustomers () {
  const customers = []

  for (let id = 0; id < 50; id++) {
    const firstName = faker.name.firstName()
    const lastName = faker.name.firstName()
    const phoneNumber = faker.phone.phoneNumberFormat()
    const zipCode = faker.address.zipCode()
    const date = faker.date.recent()

    customers.push({
      id,
      firstName,
      lastName ,
      phoneNumber ,
      zipCode,
      date
    })
  }

  return { customers }

Mock.js

Mock.jsIt is a simulation data generator, which can help separate front-end development and prototyping from back-end progress, and reduce some monotony, especially when writing automated tests.

Let me tell you something about the invincible NPM packages

Installation and examples
npm install mockjs
import Mock from "mockjs";

const Random = Mock.Random

function generateCustomers () {
  const customers = []

  for (let id = 0; id < 50; id++) {
    const firstName = Random.first()
    const lastName = Random.last()
    const province = Random.province()
    const date = Random.date()

    customers.push({
      id,
      firstName,
      lastName ,
      province,
      date
    })
  }

  return { customers }

test tools

Jest

JestIt is a convenient and easy-to-use JavaScript testing framework, with simplicity as the core appeal. You can quickly get results by writing tests through an easy-to-use and feature rich API.

Let me tell you something about the invincible NPM packages

Installation and examples

yarn add --dev jest

testsumFunction, the function of this function is to add two numbers. Create firstsum.jsFile:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

Next, create a file namedsum.test.jsFile. This file contains the actual test contents:

const sum = require("./sum");

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});

Add the following code topackage.jsonMedium:

{
  "script": {
    "test": "jest"
  }
}

Finally, runyarn test, jest will output the following information:

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

Mocha

MochaIt is a functional JavaScript testing framework that runs in node.js and browser, making asynchronous testing simple and interesting. Mocha tests run continuously, allowing flexible and accurate reporting while mapping uncapped exceptions to the correct test cases.

Installation and examples

yarn add mocha --dev

Next, create a file namedtest.jsFile. This file contains the actual test contents:

var assert = require("assert");

describe("Array", function () {
  describe("#indexOf()", function () {
    it("should return -1 when the value is not present", function () {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

Add the following code topackage.jsonMedium:

{
  "script": {
    "test": "mocha"
  }
}

Finally, runyarn test, mocha will output the following information:

$ ./node_modules/mocha/bin/mocha

  Array
    #indexOf()
      ✓ should return -1 when the value is not present


  1 passing (9ms)

Process manager and runner

Nodemon

nodemonIt is used to monitor any changes in the node.js application and automatically restart the service. It is very suitable for use in the development environment.

Nodemon will monitor the files in the startup directory, and if there are any file changes, nodemon will automatically restart the node application.

Installation and examples

yarn add  nodemon global

server.jsRepresents a node.js entry file

  "scripts": {
    "start": "nodemon server.js",
  }

PM2

PM2Is a production process manager for a node. JS application with a built-in load balancer. With it, you can keep applications active forever, reload them without downtime, and simplify common system management tasks.

Let me tell you something about the invincible NPM packages

Installation and examples
$ yarn add global pm2

You can start any application as follows (node. JS, python, ruby, binaries in $path…)

$ pm2 start app.js

Now, your application will be guarded, monitored and always active. More about process managementSee here

Once the applications start, you can easily manage them. You can list all running applications by:

$ pm2 ls

Let me tell you something about the invincible NPM packages

consultOfficial documentsTo get a complete list of PM2 functions.

Concurrently

ConcurrentlySimple and straightforward — a utility that can run multiple commands at the same time.

Let me tell you something about the invincible NPM packages

Installation and examples
yarn add concurrently global

Start the front-end webpack project and the back-end node project

//Same as package.json
"scripts": {
    "start": "concurrently \"webpack-dev-server\" \"nodemon server.js\"",
  },

Web sockets

Socket.io

Socket.IOSupport real-time, two-way and event based communication. It can run on various platforms, browsers and devices, and has good reliability and speed performance.

Let me tell you something about the invincible NPM packages

Installation and examples

Official course

WS

WSEasy to use, fast and fully tested websocket client and server implementation. It is also a powerful, less abstract alternative that is almost comparable to socket.io.

Official course


last

What else do you use in your daily workNPM tool libraryAnd? Welcome to leave your opinions in the comments area!

Friends who feel fruitful are welcomegive the thumbs-upfollowA wave!

Previous articles

React build series

  1. How to build enterprise front-end development specifications
  2. Integration of “react build” webpack 5 / react17
  3. Integrated CSS / less / sass / antd of “react build”
  4. Integrated picture / font of “react build”
  5. Redux / typescript integration of “react build”
  6. “React build” uses Redux thunk to realize Redux asynchronous operation
  7. The integrated react router / antd menu of “react build” implements routing permissions