npm
实际上是Node.js
的包管理工具(node package manager
)。javascript
为啥咱们须要一个包管理工具呢?由于咱们在Node.js
上开发时,会用到不少别人写的JavaScript
代码。若是咱们要使用别人写的某个包,每次都根据名称搜索一下官方网站,下载代码,解压,再使用,很是繁琐。因而一个集中管理的工具应运而生:你们都把本身开发的模块打包后放到npm
官网上,若是要使用,直接经过npm安装就能够直接用,不用管代码存在哪,应该从哪下载。java
更重要的是,若是咱们要使用模块A,而模块A又依赖于模块B,模块B又依赖于模块C和模块D,npm
能够根据依赖关系,把全部依赖的包都下载下来并管理起来。不然,靠咱们本身手动管理,确定既麻烦又容易出错。node
npm
的指令其实经常使用的并很少官方文档;列出来以下面:git
access
adduser
github
Add a registry user account
audit
web
Run a security audit
bin
chrome
Display npm bin folder
bugs
express
Bugs for a package in a web browser maybe
build
npm
Build a package
bundle
json
REMOVED *已删除*
cache
Manipulates packages cache
ci
Install a project with a clean slate
completion
Tab Completion for npm
config
Manage the npm configuration files
dedupe
Reduce duplication
deprecate
Deprecate a version of a package
dist-tag
Modify package distribution tags
docs
Docs for a package in a web browser maybe
doctor
Check your environments
edit
Edit an installed package
explore
Browse an installed package
help-search
Search npm help documentation
help
Get help on npm
hook
Manage registry hooks
init
create a package.json file
install-ci-test
Install a project with a clean slate and run tests
install-test
Install package(s) and run tests
install
Install a package
link
Symlink a package folder
logout
Log out of the registry
ls
List installed packages
npm
javascript package manager
outdated
Check for outdated packages
owner
Manage package owners
pack
Create a tarball from a package
ping
Ping npm registry
prefix
Display prefix
profile
Change settings on your registry profile
prune
Remove extraneous packages
publish
Publish a package
rebuild
Rebuild a package
repo
Open package repository page in the browser
restart
Restart a package
root
Display npm root
run-script
Run arbitrary package scripts
search
Search for packages
shrinkwrap
Lock down dependency versions for publication
star
Mark your favorite packages
stars
View packages marked as favorites
start
Start a package
stop
Stop a package
team
Manage organization teams and team memberships
test
Test a package
token
Manage your authentication tokens
uninstall
Remove a package
unpublish
Remove a package from the registry
update
Update a package
version
Bump a package version
view
View registry info
whoami
Display npm username
初始化建立package.json
npm init [--force|-f|--yes|-y|--scope]
npm init <@scope> (same asnpx <@scope>/create
)
npm init [<@scope>/]<name> (same asnpx [<@scope>/]create-<name>
)
搜索查看远程npm
相关资源包信息
npm search [-l|--long] [--json] [--parseable] [--no-description] [search terms ...]
aliases: s, se, find
能够是说是install
是最为常见的命令官方介绍,
npm install (with no args, in package dir)
npm install [<@scope>/]<name>
npm install [<@scope>/]<name>@<tag>
npm install [<@scope>/]<name>@<version>
npm install [<@scope>/]<name>@<version range>
npm install <git-host>:<git-user>/<repo-name>
npm install <git repo url>
npm install <tarball file>
npm install <tarball url>
npm install <folder>alias: npm i
common options: [-P|--save-prod|-D|--save-dev|-O|--save-optional] [-E|--save-exact] [-B|--save-bundle] [--no-save] [--dry-run]In global mode (ie, with -g or --global appended to the command), it installs the current package context (ie, the current working directory) as a global package. The -g or --global argument will cause npm to install the package globally rather than locally.
The -f or --force argument will force npm to fetch remote resources even if a local copy exists on disk.
上面的还介绍已经很详细了,因此这里只是讲一下npm install packageName [|--save |--save-prod|--save-dev]
的区别;
升级某个资源包或者所有资源包到某一个版本或者匹配的最新版本。
npm update [-g] [<pkg>...]
aliases: up, upgrade
移除某个资源包
npm uninstall [<@scope>/]<pkg>[@<version>]... [-S|--save|-D|--save-dev|-O|--save-optional|--no-save]
aliases: remove, rm, r, un, unlink
Node
出现以前,JavaScript
是缺乏包结构的。CommonJS
致力于改变这种现状,因而定义了包的结构规范。而NPM
的出现则是为了在CommonJS
规范的基础上,实现解决包的安装卸载,依赖管理,版本管理等问题。require
的查找机制明了以后,咱们来看一下包的细节。
一个符合CommonJS
规范的包应该是以下这种结构:
package.json
文件应该存在于包顶级目录下bin
目录下(可选)JavaScript
代码入库是index.js
,其余包含在lib
目录下doc
目录下(可选)test
目录下(可选)建立包的根目录
mkdir testpackage
初始化
npm init // 须要进行一些基本配置
建立入口文件
touch index.js
编写代码
const updateQueryString = function(url, key, value) { let urlParts = url.split('#'), hash = '', uri = urlParts.shift(), re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i'), separator = uri.indexOf('?') !== -1 ? '&' : '?', encodeKey = encodeURIComponent(key), encodeValue = encodeURIComponent(value); urlParts.length > 0 && (hash = `#${urlParts.join('#')}`); if (uri.match(re)) { return uri.replace(re, `$1${encodeKey}=${encodeValue}$2`) + hash; } else { return `${uri}${separator}${encodeKey}=${encodeValue}${hash}`; } }; // 最后的导出部分 module.exports = { updateQueryString };
测试
建立包的根目录
npm i mocha -D // 安装测试库 npm i chai -D // 安装断言库 mkdir test cd test touch index.test.js
编写测试代码
const utils = require('./../index.js'); const expect = require('chai').expect; let { updateQueryString } = utils; describe('updateQueryString函数的测试', function() { it('https://test.com/path?test=11 修改test参数为22 应该等于 https://test.com/path?test=22', function() { expect(updateQueryString('https://test.com/path?test=11', 'test', 22)).to.be.equal('https://test.com/path?test=22'); }); });
运行测试
cd .. ./node_modules/mocha/bin/mocha
npm login
,输入用户名和密码 、邮箱npm publish
发布咱们常常能够看到@angular
、@ionic
他们的包, 均可以以@开头,那么咱们的可不能够,原来angular、ionic
都属于一个组织(Organization
)只有新建立一个Organization
组织以后,才能建立@testorg/testpackname
这样的包!!!
那么咱们就能够去官网上建立咱们的Organization
,命名以后,官方步骤,
初始化
npm init --scope=<your_org_name>
npm init foo -> npx create-foo
npm init @usr/foo -> npx @usr/create-foo
npm init @usr -> npx @usr/create
package.json
里面的name
字段为@your_org_name/<pkg_name>
发布
npm publish --access public // 公开包发布
使用babel来进行一些现代JavaScript的支持,
建立配置文件
touch .babelrc
配置babel
{ "presets": [ [ "@babel/preset-env", { "targets": { "browsers": [ "last 2 versions", "safari >= 7" ], "chrome": 52, "node": "6.10.0" }, "modules": "commonjs", "useBuiltIns": "usage" } ] ], "plugins": [ "@babel/plugin-syntax-dynamic-import", "@babel/plugin-syntax-import-meta", "@babel/plugin-proposal-class-properties", "@babel/plugin-proposal-json-strings", [ "@babel/plugin-proposal-decorators", { "legacy": true } ], "@babel/plugin-proposal-function-sent", "@babel/plugin-proposal-export-namespace-from", "@babel/plugin-proposal-numeric-separator", "@babel/plugin-proposal-throw-expressions", "@babel/plugin-proposal-export-default-from", "@babel/plugin-proposal-logical-assignment-operators", "@babel/plugin-proposal-optional-chaining", [ "@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" } ], "@babel/plugin-proposal-nullish-coalescing-operator", "@babel/plugin-proposal-do-expressions" ] }
编译
./node_modules/.bin/babel src -d lib
最后的测试代码地址test-demo-npm