npm easy-to-use software packages must be collected

Posted by buzz on Wed, 02 Feb 2022 05:35:14 +0100

From: Wangdao

https://juejin.cn/post/6950584088462163982

In the face of busy schedule and urgent construction period constraints, it is undoubtedly very 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 model for each category is enough to meet the production demand. 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

lodash[1] is 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.

lodash-logo

Installation and examples

yarn add lodash

Do not abuse, try to use the method of ES. 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

`qs`[2] handles URL query strings and supports embedded objects and arrays. In short, it is to convert the parameters of object and URL address to each other

qs-github

Installation and examples

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

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

//Use II
//Pass the object parameter 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

classnames[3] conditionally group class names together

Installation and examples

yarn add classnames

Mistake ❎ 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={styles.class1 styles.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({
              styles.class1,
              styles.class2
          })>
</div>)

numeral

Numerical [4] is an NPM library specially used to format numbers. At the same time, numerical can also parse numbers in various formats.

numeral-github

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 env [5] is a script that runs cross platform settings and uses 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 regexp [6] is used to process the addresses and parameters in the url, which can easily get the data we want.

Regto exp  can be regarded as a regular expression, and regto  exp  can be regarded as a regular expression.

Installation and examples

yarn add path-to-regexp

The pathToRegexp method can be analogous to the new RegExp('xxx ') in js.

import pathToRegexp from "path-to-regexp";

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

compile is used to populate the parameter values of 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.js[7] is a fast and lightweight {moment JS [8] (enter the pure maintenance mode since September 2020, and no new version will be developed) alternative scheme. The two have similar API s, as long as you have been in contact with # moment JS, you can get started quickly js.

dayJS-office

install

yarn add dayjs

Examples

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

ESLint[9] is 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.

eslint-offcial

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, please refer to the official document [10], which has many getting started and configuration examples.

Prettier

Prettier[11] is a code formatter with distinctive style. It realizes the unified style by parsing the code and re outputting the code with its own rules (limiting the maximum length);

prettier-office

install

yarn add --dev --exact prettier

Examples

Create prettierrc.js add custom formatting rules

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

Create prettierignore add 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

stylelint[12] a powerful style rule that allows you to enforce style specifications and avoid writing wrong style code

install

yarn add stylelint stylelint-config-standard --dev

Examples

establish. stylelintrc.js and add configuration

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

Execute the lint command

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

Husky

Husky[13] 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.

HUSKY-GITHUB

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"
    }
  }
}

Here, the "hooks" of "pre commit" will run before you submit to the repository. Before pushing the code to the repository, the pre push hook is run.

🧙‍♂️ Data generator

Uuid

uuid[14] is 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.js[15] a very practical toolkit for browser and node JS generates a large amount of false data.

faker-github

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.js[16] 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.

moackjs-github

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

Jest[17] is a convenient and easy-to-use JavaScript testing framework, with simplicity as its core appeal. You can write tests through an easy-to-use and feature rich API to get results quickly.

jest-office

Installation and examples

yarn add --dev jest

Test the sum function. The function of this function is to add two numbers. First, create} sum JS file:

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

Next, create a file called sum test. JS file. 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 to package JSON:

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

Finally, run} yarn test, and Jest will output the following information:

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

Mocha

Mocha[18] is a functional javascript testing framework that runs on 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 called test JS file. 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 to package JSON:

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

Finally, run {yarn test, and 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

nodemon[19] is used to monitor node JS application and automatically restart the service, which 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.js represents a node JS entry file

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

PM2

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

p2-github

Installation and examples

$ yarn add global pm2

You can launch any application like the following (Node.js, Python, Ruby, binaries in $PATH...)

$ pm2 start app.js

Now, your app will be guarded, monitored and always active. For more information on process management, see this [21]:

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

$ pm2 ls

Refer to the official document [22] for a complete list of PM2 functions.

Concurrently

Concurrent [23] is simple and straightforward -- a utility that can run multiple commands simultaneously.

Concurrently-github

Installation and examples

yarn add concurrently global

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

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

Web sockets

Socket.io

Socket.IO[24] supports real-time, bidirectional and event based communication. It can run on various platforms, browsers and devices, and has good reliability and speed performance.

Socket.io-office

Installation and examples

Official course [25]

WS

WS[26] is an easy-to-use, fast and fully tested WebSocket client and server implementation. At the same time, it is also a powerful, less abstract and almost compatible with socket IO comparable alternatives.

Official course [27]

reference material

[1]

lodash: https://www.lodashjs.com/docs/latest

[2]

qs: https://www.npmjs.com/package/qs

[3]

classnames: https://www.npmjs.com/package/classnames

[4]

numeral: http://numeraljs.com/#format

[5]

cross-env: https://www.npmjs.com/package/cross-env

[6]

path-to-regexp: https://www.npmjs.com/package/path-to-regexp

[7]

Day.js: https://dayjs.gitee.io/docs/zh-CN/display/format

[8]

Moment.js: http://momentjs.cn/

[9]

ESLint: https://eslint.bootcss.com/docs/user-guide/getting-started

[10]

Official documents: https://eslint.org/

[11]

Prettier: https://prettier.bootcss.com/docs/index.html

[12]

stylelint: https://stylelint.io/user-guide/get-started

[13]

Husky: https://www.npmjs.com/package/husky

[14]

uuid: https://www.npmjs.com/package/uuid

[15]

faker.js: https://www.npmjs.com/package/faker

[16]

Mock.js: http://mockjs.com/examples.html

[17]

Jest: https://www.jestjs.cn/docs/getting-started

[18]

Mocha: https://mochajs.cn/

[19]

nodemon: https://www.npmjs.com/package/nodemon

[20]

PM2: https://www.npmjs.com/package/pm2

[21]

See here: https://pm2.keymetrics.io/docs/usage/quick-start/

[22]

Official documents: https://pm2.io/

[23]

Concurrently: https://www.npmjs.com/package/concurrently

[24]

Socket.IO: https://socketio.bootcss.com/

[25]

Official tutorial: https://socketio.bootcss.com/get-started/chat/

[26]

WS: https://www.npmjs.com/package/ws

[27]

Official tutorial: https://www.npmjs.com/package/ws

Topics: Javascript Front-end