发布到 NPM
npm 是 JavaScript 生态圈中的包管理器,有众多的开发者和团队在 npm 上发布了许多优质组件,为 JavaScript 生态圈的繁荣做出了自己的贡献。在这里我们就来学习一下如何将自己的代码发布到 npm 上去。
npm init
首先我们需要初始化一个 npm 模块的描述文件 package.json
,我们新建一个目录 random-string
,在目录下执行:
npm init
接下来根据提示填写对应的信息,完成后会生成 package.json
文件
{
"name": "random-string",
"version": "1.0.0",
"description": "generates a random string",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
关联 *.d.ts
如果你为你的库编写了对应的 *.d.ts 文件,你可以在types
属性内指定文件所在位置
{
"name": "random-string",
"version": "1.0.0",
"description": "generates a random string",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
编写代码
默认的 npm package 入口文件是 index.js,我们在目录下新建一个 index.js 文件,并写一个简单的随机字符串生成函数。
// index.js
/**
* 随机字符串生成函数
*/
export default function() {
return Math.random()
.toString(36)
.substr(2)
.toString();
}
兼容多种模块化的引入方式
在 JavaScript 生态圈建立的早期,由于官方规范的缺失,社区形成了多套模块化方案(AMD、CommonJS、UMD)。我们可以兼容一下各种模块化方案的引入。
/**
* 兼容多种模块化方案
*/
(function(global, factory) {
typeof exports === "object" && typeof module !== "undefined"
? (module.exports = factory())
: typeof define === "function" && define.amd
? define(factory)
: (global.Qarticles = factory());
})(this, function() {
/**
* 随机字符串生成函数
*/
return Math.random()
.toString(36)
.substr(2)
.toString();
});
发布模块
注册 NPM 账号
编写好我们的模块之后,现在需要注册 NPM 账号。https://www.npmjs.com/signup
本地登录 NPM 账号
npm login
发布
npm publish