<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【工具】分享一些強無敵的 NPM 軟件包

          共 14175字,需瀏覽 29分鐘

           ·

          2021-07-10 00:24

          面對繁忙的日程安排與緊迫的工期限制,選擇能夠切實提升生產(chǎn)率的工具無疑至關(guān)重要。

          在這里,我整理出一份個人最喜歡的 NPM 軟件包清單。為了便于瀏覽,我還對它們進行了分類,希望呈現(xiàn)出更加清晰的結(jié)構(gòu)。

          當然,大家不必全數(shù)安裝與學(xué)習(xí)。在大多數(shù)情況下,每個類別選擇一款就足以解決生產(chǎn)需求。我只是想多提供一點替代方案,幫助每位讀者朋友找到最適合自己的選項。閑言少敘,咱們馬上開始!

          ?? 實用工具

          Lodash

          lodash[1]是一套現(xiàn)代 JavaScript 實用程序庫,提供模塊化、性能與多種附加功能??商峁╆P(guān)于 JavaScript 數(shù)組、對象及其他數(shù)據(jù)結(jié)構(gòu)的多種實用功能。

          lodash-logo

          安裝及示例

          yarn add lodash

          不要濫用,盡量使用 ES 自帶方法 。我常用的一些方法如下

          // -----------------------------深度比較兩個對象的值是否全相等
          import { isEqual, cloneDeep, uniqBy, sortBy } from "lodash";

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

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

          object === other;
          // => false

          // -----------------------------深拷貝
          const objects = [{ a: 1 }, { b: 2 }];

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

          // -----------------------------數(shù)組去重
          uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], "x");
          // => [{ 'x': 1 }, { 'x': 2 }]

          // -----------------------------數(shù)組排序
          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] 處理 URL 查詢字符串,支持內(nèi)嵌對象和數(shù)組。簡而言之,就是將對象和 URL 地址的參數(shù)互相轉(zhuǎn)換

          qs-github
          安裝及示例
          yarn add qs
          import { parse, stringify } from "qs";

          // 用途一
          // 將 瀏覽器上 URL地址參數(shù)轉(zhuǎn)換為對象(字符串轉(zhuǎn)對象)
          const urlParams = parse(window.location.href.split("?")[1]);

          // 用途二
          // 將對象參數(shù) 傳遞給到后端接口--GET 請求  (對象轉(zhuǎn)字符串)
          const params = {
            name"wang",
            age"18",
            sex"女",
          };

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

          classnames

          classnames[3]有條件地將類名組合在一起

          安裝及示例

          yarn add classnames

          錯誤 ? 代碼示例: React 原生動態(tài)添加多個樣式類名會報錯:

          import styles from "./index.less";

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

          修改為如下代碼即可解決

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

          import styles from "./index.less";

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

          numeral

          numeral[4]是一個專門用來格式化數(shù)字的 NPM 庫,同時 numeral 還能解析各種格式的數(shù)字。

          numeral-github

          安裝及示例

          yarn add numeral
          import numeral from "numeral";

          // 解析數(shù)字
          numeral("10,000.12"); // 10000.12
          numeral("$10,000.00"); // 10000
          numeral("3.467TB"); // 3467000000000
          numeral("-76%"); // -0.76

          // 格式化

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

          cross-env

          cross-env[5]是一個運行跨平臺設(shè)置和使用環(huán)境變量的腳本

          安裝及示例
          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]用來處理 url 中地址與參數(shù),能夠很方便得到我們想要的數(shù)據(jù)。

          js 中有 RegExp 方法做正則表達式校驗,而 path-to-regexp 可以看成是 url 字符串的正則表達式。

          安裝及示例

          yarn add path-to-regexp

          pathToRegexp方法可以類比于 js 中 new RegExp('xxx')。

          import pathToRegexp from "path-to-regexp";

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

          compile用于填充 url 字符串的參數(shù)值。

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

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

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

          ?? 日期格式

          Day.js

          Day.js[7] 是一款快速且輕量化的 Moment.js[8](自 2020 年 9 月起進入純維護模式,不再開發(fā)新版本) 替代方案。二者擁有類似的 API,只要你接觸過 Moment.js,就能夠快速上手 Day.js。

          dayJS-office

          安裝

          yarn add dayjs

          示例

          import dayjs from "dayjs";

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

          // -------------------------以字符串形式返回 當前時間
          const data = dayjs().format(myformat);
          // =>  2020-11-25 12:25:56

          // -------------------------日期格式化
          const data1 = dayjs("2020-11-25 12:25:56").format("YYYY/MM/DD HH/mm/ss");
          // => 2020/11/25 12/25/56

          // -------------------------多久之前
          var relativeTime = require("dayjs/plugin/relativeTime");
          dayjs.extend(relativeTime);
          const data1 = dayjs("2020-11-25 11:40:41").fromNow();

          // =>

          ?? Linters 與格式化工具

          ESLint

          ESLint[9] 是一個很好用的工具,可用來避免代碼錯誤并強制開發(fā)團隊使用編碼標準。ESLint 是用于識別和報告 ECMAScript/JavaScript 代碼中模式的工具。ESLint 具備全面的可插入特性,每項規(guī)則對應(yīng)一款插件,供你在運行時添加更多內(nèi)容。

          eslint-offcial
          安裝和使用
          $ yarn add eslint --dev

          然后,你應(yīng)該設(shè)置一個配置文件:

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

          之后,你可以在任何文件或目錄上運行 ESLint,如下所示:

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

          有關(guān)更多說明,請參閱官方文檔[10],其中有許多入門和配置示例。

          Prettier

          Prettier[11] 是一款風格鮮明的代碼格式化程序。它通過解析代碼并使用自己的規(guī)則(限定最大行長)對代碼進行重新輸出,借此實現(xiàn)統(tǒng)一的樣式;

          prettier-office

          安裝

          yarn add --dev --exact prettier

          示例

          創(chuàng)建 .prettierrc.js 加入自定義格式化規(guī)則

          module.exports = {
            trailingComma"es5",
            tabWidth4,
            semifalse,
            singleQuotetrue,
          };

          創(chuàng)建 .prettierignore 加入需要忽略的文件或目錄

          # Ignore artifacts:
          build
          coverage

          執(zhí)行格式化命令

          # 格式化src目錄下的所有js文件

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

          stylelint

          stylelint[12] 一個強大的樣式規(guī)則,可以讓你強制執(zhí)行樣式規(guī)范,避免書寫錯誤的樣式代碼

          安裝

          yarn add stylelint stylelint-config-standard --dev

          示例

          創(chuàng)建.stylelintrc.js并加入配置

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

          執(zhí)行 lint 命令

          # 檢查 src目錄下所有css文件是否符合規(guī)范
          npx stylelint "src/**/*.css"

          Husky

          Husky[13] 可以幫助我們簡單直接地實現(xiàn) git hooks。你們團隊正在協(xié)作開發(fā),并希望在整個團隊中推行一套編碼標準?沒問題!有了 Husky,你就可以要求所有人在提交或推送到存儲庫之前自動完成 lint 并測試其代碼。

          HUSKY-GITHUB
          安裝及示例
          yarn add husky --dev

          下面是一個實現(xiàn) husky hooks 的示例:

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

          這里 pre-commit 的 hooks 會在你提交到存儲庫之前運行。在將代碼推送到存儲庫之前,將運行 pre-push hook。


          ???♂? 數(shù)據(jù)生成器

          Uuid

          uuid[14]是一個便捷的微型軟件包,能夠快速生成更為復(fù)雜的通用唯一標識符(UUID)。

          安裝及示例

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

          faker.js

          faker.js[15]非常實用的工具包,用于在瀏覽器及 Node.js 中生成大量假數(shù)據(jù)。

          faker-github

          安裝及示例

          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] 是一個模擬數(shù)據(jù)生成器,可幫助前端開發(fā)和原型與后端進度分開,并減少某些單調(diào)性,尤其是在編寫自動化測試時。

          moackjs-github
          安裝及示例
          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 }

          ?? 測試工具

          Jest

          Jest[17] 是一款便捷好用的 JavaScript 測試框架,以簡單為核心訴求。您可以通過易于上手且功能豐富的 API 編寫測試,從而快速獲取結(jié)果。

          jest-office

          安裝及示例

          yarn add --dev jest

          測試sum函數(shù),這個函數(shù)的功能是兩數(shù)相加。首先創(chuàng)建 sum.js 文件:

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

          接下來,創(chuàng)建名為 sum.test.js 的文件。這個文件包含了實際測試內(nèi)容:

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

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

          將如下代碼添加到 package.json 中:

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

          最后,運行 yarn test ,Jest 將輸出如下信息:

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

          Mocha

          Mocha[18] 是一個功能豐富的 javascript 測試框架,運行在 node.js 和瀏覽器中,使異步測試變得簡單有趣。Mocha 測試連續(xù)運行,允許靈活和準確的報告,同時將未捕獲的異常映射到正確的測試用例。

          安裝及示例

          yarn add mocha --dev

          接下來,創(chuàng)建名為 test.js 的文件。這個文件包含了實際測試內(nèi)容:

          var assert = require("assert");

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

          將如下代碼添加到 package.json 中:

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

          最后,運行 yarn test ,Mocha 將輸出如下信息:

          $ ./node_modules/mocha/bin/mocha

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


            1 passing (9ms)

          ????? 進程管理器與運行器

          Nodemon

          nodemon[19]用來監(jiān)視 node.js 應(yīng)用程序中的任何更改并自動重啟服務(wù),非常適合用在開發(fā)環(huán)境中。

          nodemon 將監(jiān)視啟動目錄中的文件,如果有任何文件更改,nodemon 將自動重新啟動 node 應(yīng)用程序。

          安裝及示例

          yarn add  nodemon global

          server.js表示一個 Node.js 入口文件

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

          PM2

          PM2[20] 是一個具有內(nèi)置負載均衡器的 Node.js 應(yīng)用程序的生產(chǎn)流程管理器。有了它,你就可以讓應(yīng)用程序永遠保持活躍,可以在不停機的前提下重新加載它們,并簡化常見的系統(tǒng)管理任務(wù)。

          p2-github
          安裝及示例
          $ yarn add global pm2

          你可以像下面一樣啟動任何應(yīng)用程序(Node.js、Python、Ruby、$PATH 中的二進制文件……)

          $ pm2 start app.js

          現(xiàn)在,你的應(yīng)用將被守護、監(jiān)控并永遠保持活躍。有關(guān)流程管理的更多信息見此[21]

          應(yīng)用程序啟動后,你就可以輕松管理它們??梢酝ㄟ^以下方法列出所有正在運行的應(yīng)用程序:

          $ pm2 ls

          查閱官方文檔[22],以獲取 PM2 功能給的完整列表。

          Concurrently

          Concurrently[23]簡單而直接——可同時運行多條命令的實用工具。

          Concurrently-github
          安裝及示例
          yarn add concurrently global

          時啟動前端 webpack 項目和 后端 node 項目

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

          Web sockets

          Socket.io

          Socket.IO[24] 支持實時、雙向、基于事件的通信功能。它能夠運行在各類平臺、瀏覽器及設(shè)備之上,且擁有良好的可靠性與速度表現(xiàn)。

          Socket.io-office

          安裝及示例

          官方教程[25]

          WS

          WS[26]易于使用、快速且經(jīng)過全面測試的 WebSocket 客戶端與服務(wù)器實現(xiàn)。同時也是一套強大、抽象度更低且?guī)缀跄軌蚺c Socket.io 相媲美的替代方案。

          官方教程[27]


          參考資料

          [1]

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

          [2]

          qshttps://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]

          官方文檔: 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]

          見此: https://pm2.keymetrics.io/docs/usage/quick-start/

          [22]

          官方文檔: https://pm2.io/

          [23]

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

          [24]

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

          [25]

          官方教程: https://socketio.bootcss.com/get-started/chat/

          [26]

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

          [27]

          官方教程: https://www.npmjs.com/package/ws


          轉(zhuǎn)自:ask_the_sky

          https://juejin.cn/post/6950584088462163982


          1. JavaScript 重溫系列(22篇全)
          2. ECMAScript 重溫系列(10篇全)
          3. JavaScript設(shè)計模式 重溫系列(9篇全)
          4. 正則 / 框架 / 算法等 重溫系列(16篇全)
          5. Webpack4 入門(上)|| Webpack4 入門(下)
          6. MobX 入門(上) ||  MobX 入門(下)
          7. 120+篇原創(chuàng)系列匯總

          回復(fù)“加群”與大佬們一起交流學(xué)習(xí)~

          點擊“閱讀原文”查看 120+ 篇原創(chuàng)文章



          瀏覽 98
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  亚欧操逼| 亚洲无码三级 | 色天堂色男人 | 天天干天天操天天舔 | 91十八禁|