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