发布到 NPM

npm 是 JavaScript 生态圈中的包管理器,有众多的开发者和团队在 npm 上发布了许多优质组件,为 JavaScript 生态圈的繁荣做出了自己的贡献。在这里我们就来学习一下如何将自己的代码发布到 npm 上去。

npm init

首先我们需要初始化一个 npm 模块的描述文件 package.json,我们新建一个目录 random-string,在目录下执行:

  1. npm init

接下来根据提示填写对应的信息,完成后会生成 package.json 文件

  1. {
  2. "name": "random-string",
  3. "version": "1.0.0",
  4. "description": "generates a random string",
  5. "main": "index.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1"
  8. },
  9. "author": "",
  10. "license": "ISC"
  11. }

关联 *.d.ts

如果你为你的库编写了对应的 *.d.ts 文件,你可以在types 属性内指定文件所在位置

  1. {
  2. "name": "random-string",
  3. "version": "1.0.0",
  4. "description": "generates a random string",
  5. "main": "index.js",
  6. "types": "index.d.ts",
  7. "scripts": {
  8. "test": "echo \"Error: no test specified\" && exit 1"
  9. },
  10. "author": "",
  11. "license": "ISC"
  12. }

编写代码

默认的 npm package 入口文件是 index.js,我们在目录下新建一个 index.js 文件,并写一个简单的随机字符串生成函数。

  1. // index.js
  2. /**
  3. * 随机字符串生成函数
  4. */
  5. export default function() {
  6. return Math.random()
  7. .toString(36)
  8. .substr(2)
  9. .toString();
  10. }

兼容多种模块化的引入方式

在 JavaScript 生态圈建立的早期,由于官方规范的缺失,社区形成了多套模块化方案(AMD、CommonJS、UMD)。我们可以兼容一下各种模块化方案的引入。

  1. /**
  2. * 兼容多种模块化方案
  3. */
  4. (function(global, factory) {
  5. typeof exports === "object" && typeof module !== "undefined"
  6. ? (module.exports = factory())
  7. : typeof define === "function" && define.amd
  8. ? define(factory)
  9. : (global.Qarticles = factory());
  10. })(this, function() {
  11. /**
  12. * 随机字符串生成函数
  13. */
  14. return Math.random()
  15. .toString(36)
  16. .substr(2)
  17. .toString();
  18. });

发布模块

注册 NPM 账号

编写好我们的模块之后,现在需要注册 NPM 账号。https://www.npmjs.com/signup

本地登录 NPM 账号

  1. npm login

发布

  1. npm publish