5分钟发布你的第一个npm包

1,090 阅读2分钟

npm是什么

npm是nodejs的包管理工具

npm有什么用

可以将自己的代码发布到npm上供别人下载使用,也可以在npm上下载其他人共享的代码。

如何使用npm

npm是nodejs内置的包管理工具,安装完nodejs后就可以使用npm了。

常用指令

安装:

npm install xxx

全局安装 npm install xxx -g

生产环境安装 npm install xxx -S 存放于devDependencies节点

开发环境安装 npm install xxx -D 存放于dependencies节点

devDependencies 里面的插件只用于开发环境,不用于生产环境,而 dependencies 是需要发布到生产环境的

上传你的第一个npm包

1.npm网站注册账号密码

注册地址地址:https://www.npmjs.com/signup

2.初始化项目

npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (npmdemo) zxb-npmdemo-wlww
version: (1.0.01.0.0
description: test
entry point: (index.js)
test command:
git repository:
keywords:
author: zd
license: (ISC)
About to write to F:\个人\npmDemo\package.json:

{
  "name""npmdemo",
  "version""1.0.0",
  "description""test",
  "main""index.js",
  "scripts": {
    "test""echo \"Error: no test specified\" && exit 1"
  },
  "author""zd",
  "license""ISC"
}

3.编写代码

创建index.js

export function say(){
  console.log("hello word")
}

4.登录npm

npm login

5.发布npm包

npm publish

6.新建项目安装已发布的npm包

npm install zxb-npmdemo-wlww

在文件中引入刚安装的包

import {say} from 'zxb-npmdemo-wlww
say()

控制台输出:

hello word

7.更新npm包

index.js中新增方法

export function say(){
  console.log("hello word")
}

export function sayHi(){
  console.log("hi word")
}

更改版本号,重新发布 npm publish

8.在项目中更新npm包

npm update zxb-npmdemo-wlww

9.在项目中应用新方法

import {say,sayHi} from 'zxb-npmdemo-wlww'

sayHi() 控制台输出 hi word

10.在npm上删除npm包

npm unpublish --force

由于npm安全策略调整,这条命令只能删除24小时之内发布的最新版本