摘要:什么是npm?
npm是javascript著名的包管理工具,是前端模块化下的一个标志性产物
简单的说,就是通过npm下载模块,复用已有的代码,提高工作效率
一、创建npm账号
进入到https://www.npmjs.com/,注册一个npm账号
二、初始化一个简单的项目发布
1.新建一个空文件夹 例如 test-tool
2.执行命令进入目录:cd test-tool
3.执行如下命令,初始化项目。默认一路回车
npm init
PS D:\01.workspace\test-tool> 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: (test-tool)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\01.workspace\test-tool\package.json:
{
"name": "test-tool",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
PS D:\01.workspace\test-tool>
4.在 test-tool文件夹中创建一个文件名为index.js的文件,简单的写了一下内容
!function(){
console.log(`这是引入的包入口`)
}()
{
"name": "test-tool",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
package.json简介:
name:发布的包名,默认是上级文件夹名。不得与现在npm中的包名重复。包名不能有大写字母/空格/下滑线!
version:你这个包的版本,默认是1.0.0。对于npm包的版本号有着一系列的规则,模块的版本号采用X.Y.Z的格式,具体体现为:
1、修复bug,小改动,增加z。
2、增加新特性,可向后兼容,增加y
3、有很大的改动,无法向下兼容,增加x
description:项目简介
mian:入口文件,默认是index.js,可以修改成自己的文件
scripts:包含各种脚本执行命令
test:测试命令。
author:写自己的账号名
license:这个直接回车,开源文件协议吧,也可以是MIT,看需要吧。
三、如果本机第一次发布包(非第一次可忽略)
在终端输入如下命令,提示输入账号,密码和邮箱,然后将提示创建成功,具体如下图。
npm adduser
【注意】npm adduser成功的时候默认你已经登陆了,所以可跳过第四步。
四、如果本机第一次发布包(非第一次可忽略)
在终端输入npm login,然后输入你创建的账号和密码,和邮箱,登陆,结果同步骤三。
五、npm publish 发包
注意:如果项目里有部分私密的代码不想发布到npm上,可以将它写入.gitignore 或.npmignore中,上传就会被忽略了
六、查询发布的包
到npm官网全局搜索即可
七、安装使用方式
进入项目目录运行
npm (或cnpm) install XXXX (XXXX是我们刚发布的包)
和其它包使用方式一致,具体使用可以看源码介绍或者README.md。
八、如何撤销发布的包
终端执行 npm unpublish
例如:
npm unpublish test-tool@1.0.0 删除某个版本
npm unpublish test-tool --force 删除整个npm市场的包
npm unpublish的推荐替代命令
npm deprecate <pkg>[@<version>] <message>
使用这个命令,并不会在社区里撤销你已有的包,但会在任何人尝试安装这个包的时候得到警告
例如:
npm deprecate z-tool
【注意】如果报权限方面的错,加上--force