美文网首页
如何将JS函数库发布到NPM

如何将JS函数库发布到NPM

作者: ABC周毅 | 来源:发表于2020-05-13 16:45 被阅读0次

开发久了,你会发现在很多项目中,部分函数是通用的。大部分小伙伴的做法是从一个项目拷贝到另一个项目。有时会忘记某个函数是写在那个项目当中。此时,不如将平时常用的函数整理,发布一个自己的npm包。废话不多说:接下来,让我一步步搭建属于自己的npm包。

1、新建一个空白文件夹,执行如下命令

npm init -y

// 常用配置说明如下
npm 常用配置说明 name - 包名。
version - 包的版本号
scripts - 配置可被 npm 执行的命令
config - 设置配置属性,配合 scripts 属性使用
dependencies - 包依赖,会同该包一起安装
devDependencies - 包依赖,不会同该包一起安装
peerDependencies - 声明使用该插件时,宿主环境必需存在的插件
engines - 指定代码运行环境
os - 指定代码运行的操作系统
publishConfig - 发布时的配置
main - 其他项目引用该包时的入口文件
description - 包描述,可用于 npm 官网搜索
keywords - 包关键字,可用于 npm 官网搜索
homepage - 包的官网
urlbugs - 提交包 bug 的方式
license - 包许可证
author - 包作者,只能存在一个作者
contributors - 包的其他贡献者姓名

2、创建如下目录结构(后面说明具体作用)

// 后面具体说明每个文件的用处
.
├── 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 = {
    // 设置mode为none避免默认压缩
    mode: 'none',
    // lzytool.min 为压缩文件,用于生产环境
    entry: {
        'lzytool': path.join(__dirname, "src/index.js"),
        'lzytool.min': path.join(__dirname, "src/index.js"),
    },
    // library相关文档
    // 传送门: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以上语法转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']
                    }
                }
            }
        ]
    },
    // 创建 TerserPlugin 实例,覆盖默认的压缩配置。
    // 传送门:https://webpack.js.org/plugins/terser-webpack-plugin/
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                include: /\.min\.js$/
            })
        ]
    }
}

6、编写一个的函数

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

// 编辑 /src/index.js 将 add 函数导出
export { default as add } from './add'

7、配置 package.json

// 主要配置 scripts
{
  "name": "zytool",
  "version": "1.0.0",
  "description": "整理常用的JS函数库",
  "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"
  },
}
// 执行打包命令
npm run build

// 得到如下结果
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发包

.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('加法函数的测试', function () {
    it('1 加 1 应该等于 2', function () {
        expect(add(1, 1)).to.be.equal(2);
    });
});

// 执行 npm run test
// 得到如下结果

加法函数的测试
    ✓ 1 加 1 应该等于 2

  1 passing (3ms)

11、注册NPM账号

传送门 https://www.npmjs.com/

12、登录 npm 、发布包

 npm login
// 输入你刚注册的用户名和密码

npm publish 
// 发包

以上只是发布一个简单的JS函数包到NPM的过程。
相关配置说明可以通过传送门查看文档哈。

相关文章

网友评论

      本文标题:如何将JS函数库发布到NPM

      本文链接:https://www.haomeiwen.com/subject/otznnhtx.html