如何將JS函數(shù)庫發(fā)布到NPM

開發(fā)久了,你會發(fā)現(xiàn)在很多項目中,部分函數(shù)是通用的。大部分小伙伴的做法是從一個項目拷貝到另一個項目。有時會忘記某個函數(shù)是寫在那個項目當中。此時,不如將平時常用的函數(shù)整理,發(fā)布一個自己的npm包。廢話不多說:接下來,讓我一步步搭建屬于自己的npm包。

1、新建一個空白文件夾,執(zhí)行如下命令

npm init -y

// 常用配置說明如下
npm 常用配置說明 name - 包名。
version - 包的版本號
scripts - 配置可被 npm 執(zhí)行的命令
config - 設(shè)置配置屬性,配合 scripts 屬性使用
dependencies - 包依賴,會同該包一起安裝
devDependencies - 包依賴,不會同該包一起安裝
peerDependencies - 聲明使用該插件時,宿主環(huán)境必需存在的插件
engines - 指定代碼運行環(huán)境
os - 指定代碼運行的操作系統(tǒng)
publishConfig - 發(fā)布時的配置
main - 其他項目引用該包時的入口文件
description - 包描述,可用于 npm 官網(wǎng)搜索
keywords - 包關(guān)鍵字,可用于 npm 官網(wǎng)搜索
homepage - 包的官網(wǎng)
urlbugs - 提交包 bug 的方式
license - 包許可證
author - 包作者,只能存在一個作者
contributors - 包的其他貢獻者姓名

2、創(chuàng)建如下目錄結(jié)構(gòu)(后面說明具體作用)

// 后面具體說明每個文件的用處
.
├── README.md
├── babel.config.js
├── dist
│   └── lzytool.min.js
├── npm-publish.sh
├── package.json
├── src
│   ├── add.js
│   └── index.js
├── test
│   └── add.test.js
├── .mocharc.js
├── .npmignore
└── webpack.config.js

3、安裝依賴包

// 用于babel配置
npm install @babel/cli @babel/core @babel/preset-env @babel/polyfill -D

// 用于單元測試
npm install @babel/register babel-plugin-transform-object-rest-spread chai mocha -D

// 用于webpack打包
npm install webpack webpack-cli babel-loader -D

4、配置bable

// 編輯 /babel.config.js 文件
// 傳送門:https://www.babeljs.cn/docs
module.exports = {
    "presets": [
        ["@babel/preset-env", {
            "targets": {
                "ie": "8",
                "chrome": "58",
            },
        }]
    ],
    "plugins": [
        ["transform-object-rest-spread", { "useBuiltIns": true }]
    ]
}

5、配置 webpack

const path = require("path");
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
    // 設(shè)置mode為none避免默認壓縮
    mode: 'none',
    // lzytool.min 為壓縮文件,用于生產(chǎn)環(huán)境
    entry: {
        'lzytool': path.join(__dirname, "src/index.js"),
        'lzytool.min': path.join(__dirname, "src/index.js"),
    },
    // library相關(guān)文檔
    // 傳送門:https://www.webpackjs.com/configuration/output/#output-library
    output: {
        path: path.join(__dirname, "dist"),
        filename: '[name].js',
        library: 'webpackNumbers',
        libraryTarget: 'umd',
        globalObject: 'this',
    },

    // 配置 bable 模塊,用于ES6以上語法轉(zhuǎn)ES5
    // 傳送門:https://webpack.js.org/loaders/babel-loader/#root
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    },
    // 創(chuàng)建 TerserPlugin 實例,覆蓋默認的壓縮配置。
    // 傳送門:https://webpack.js.org/plugins/terser-webpack-plugin/
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                include: /\.min\.js$/
            })
        ]
    }
}

6、編寫一個的函數(shù)

//  編輯 /src/add.js
function add(x, y) {
    return x + y;
}
export default add;

// 編輯 /src/index.js 將 add 函數(shù)導(dǎo)出
export { default as add } from './add'

7、配置 package.json

// 主要配置 scripts
{
  "name": "zytool",
  "version": "1.0.0",
  "description": "整理常用的JS函數(shù)庫",
  "main": "./dist/lzytool.min.js",
  "scripts": {
    "build": "webpack", // 用于打包
    "test": "mocha --require @babel/register" //用于單元測試
  },
  "author": "ZhouYi",
  "license": "MIT",
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.6",
    "@babel/polyfill": "^7.8.7",
    "@babel/preset-env": "^7.9.6",
    "@babel/register": "^7.9.0",
    "babel-loader": "^8.1.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "chai": "^4.2.0",
    "mocha": "^7.1.2",
    "terser-webpack-plugin": "^3.0.1",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.11"
  },
}
// 執(zhí)行打包命令
npm run build

// 得到如下結(jié)果
Hash: f10c45e2a9f76ae0b16f
Version: webpack 4.43.0
Time: 1100ms
Built at: 2020-05-13 16:35:02
         Asset      Size  Chunks             Chunk Names
lzytool.min.js  1.29 KiB       0  [emitted]  lzytool.min
Entrypoint lzytool.min = lzytool.min.js
[0] ./src/index.js 39 bytes {0} [built]
[1] ./src/add.js 59 bytes {0} [built]

8、配置 .mocharc.js

// 用于單元測試
module.exports = {
    diff: true,
    extension: ['js'],
    package: './package.json',
    reporter: 'spec',
};

9、配置 .npmignore

// 用于npm發(fā)包

.DS_Store
.mocharc.js
node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
babel.config.js
webpack.config.js
npm-publish.sh

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

10、單元測試

// 編輯 /test/add.text.js

import chai from 'chai';
import { add } from '../dist/lzytool.min';

let expect = chai.expect;

describe('加法函數(shù)的測試', function () {
    it('1 加 1 應(yīng)該等于 2', function () {
        expect(add(1, 1)).to.be.equal(2);
    });
});

// 執(zhí)行 npm run test
// 得到如下結(jié)果

加法函數(shù)的測試
    ? 1 加 1 應(yīng)該等于 2

  1 passing (3ms)

11、注冊NPM賬號

傳送門 https://www.npmjs.com/

12、登錄 npm 、發(fā)布包

 npm login
// 輸入你剛注冊的用戶名和密碼

npm publish 
// 發(fā)包

以上只是發(fā)布一個簡單的JS函數(shù)包到NPM的過程。
相關(guān)配置說明可以通過傳送門查看文檔哈。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容