前端学习 node 快速入门 系列 —— npm

其他章节请看:

前端学习 node 快速入门 系列

npm

npm 是什么

npm 是 node 的包管理器,绝大多数 javascript 相关的包都放在 npm 上。

所谓,就是别人提供出来供他人使用的项目。可以是简单的几行代码,可以是 jQuery 这种类库,也可以是框架 express ,还可以是 webpack 这样的工具。

npm 用于解决前端共享问题。

以前我们需要使用 jQuery、bootstrap 等其他库,需要这么做:

  1. 进入 jQuery 和 bootstrap 等其他库的官网
  2. 将库下载到本地
  3. 本地引入库

npm 的作者希望简化这个过程,比如只需要执行一条命令 npm install jquery,就能将 jquery 下载到本地。

实现的思路大概是这样:

  1. npm 作者发邮件给 jQuery 和 bootstrap 的作者,让他们把项目放到 npm 上
  2. jQuery 和 bootstrap 的作者由于不认识发邮件的人,当然会拒绝
  3. node 的作者缺少一个包管理器,而 npm 作者有一个包管理器,于是两人抱团取暖,node 内置了 npm
  4. 后来 node 火了,npm 也出名了,于是 jQuery 和 bootstrap 的作者主动把项目放到 npm 上
  5. 现在基于 node 开发的环境,如果需要引入什么包,只需要一个命令

初步认识 node一文中,我们已经成功安装了 node,而 node 内置了 npm,现在我们就可以用 npm 下载一个包体验一下:

$ node --version // 查看 node 是否已成功安装
v12.18.1

$ npm --version // 查看 npm 版本
6.14.5

$ npm install jquery // {1}
npm WARN saveError ENOENT: no such file or directory, open 'D:\package.json'
...
...
+ jquery@3.6.0
added 1 package from 1 contributor and audited 1 package in 1.692s
found 0 vulnerabilities

运行 npm install jquery(行{1})会将 jquery 下载到项目根目录的 node_modules 文件夹中。

npm 另一个意思就是 npm 网站,npm 的包就存在那里。如果可以在该网站中搜索到相应的包名(PackageName),那我们就可以通过 npm install PackageName 下载。

输入 npm install hello-world ,看看会发生什么...

package.json

Node项目中 package.json 就是项目的核心。

运行 npm init 能创建一个 package.json 文件。请看示例:

// 输入 npm init 回车,会依次让你输入关于项目的配置信息,这里一路回车
$ npm init
...
package name: (test2)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to D:\test2\package.json:

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

Is this OK? (yes) yes

输入完 yes 后,会在项目根目录下生成一个 package.json 的文件。内容如下:

{
  "name": "test2", // 名称
  "version": "1.0.0", // 版本
  "description": "", // 描述
  "main": "index.js", // 入口文件
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

如果你打算发布软件包,package.json 中最重要的字段是 name 和 version,因为它们是必填;如果你不打算发布,name 和 version 则是可选的。

main 字段是程序主入口点。如果我安装了一个包(xx),然后执行 require(xx),将返回入口文件的导出模块。请看示例:

// 下载包
$ npm install underscore

// 创建文件 1.js
let _ = require('underscore')
console.log(_)

// 运行 1.js - 输出导出模块
$ node 1
[Function: _] {
  VERSION: '1.12.0',
  toPath: [Function: toPath],
  iteratee: [Function: iteratee],
  templateSettings: {
    evaluate: /<%([\s\S]+?)%>/g,
  ...
  ...

// 修改 underscore 的主入口文件 node_modules\underscore\package.json 
{
    "main": "underscore.js",
    // 改为
    "main": "underscore2.js", // {1}
}

// 创建 node_modules\underscore\underscore2.js,内容如下:
exports.name = 'aaron'

// 运行 - 导出模块变成 { name: 'aaron' }
$ node 1
{ name: 'aaron' } // {2}

通过修改 underscore 的主入口文件(行{1}),最终 underscore 导出的模块是 { name: 'aaron' }(行{2})

我们也可以通过 npm init -y 跳过向导,快速生成 package.json。

npm install

执行 npm init -y 快速生成 package.json 文件后,再运行 npm install jquery 来安装 jquery,会在 package.json 中增加 dependencies 字段。内容如下:

{
  ...
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.6.0"
  }
}

dependencies 字段声明了此项目依赖的包

:网上有的文章说执行 npm install jquery,不会在 package.json 中增加 dependencies 项,可能以前的 npm 不会。笔者的 npm 是 6.14.5,参考的文档是 npm-install V6,里面说 npm install 默认将软件包保存到 dependencies 中。

此外还可以控制保存软件包的位置和方式,请看示例:

// 不保存在 dependencies
$ npm install jquery --no-save 

// 保存在 devDependencies
$ npm i jquery --save-dev

执行 npm install (不带任何参数)将安装 package.json 中列出的所有依赖包。请看示例:

{
  ...
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.6.0"
  },
  "devDependencies": {
    "underscore": "^1.12.0"
  }
}

package.json 中列出了两个依赖,执行 npm install 将会把 jquery 和 underscore 下载到项目根目录的 node_modules 文件夹中。

当安装包或删除包,npm 都会生成或更新 package-lock.json 文件。npm 5 以前没有 package-lock.json 这个文件。笔者的 npm 是 6.14.5,运行 npm install jquery,package.json 和 package-lock.json 的内容如下:

// package.json
{
  "dependencies": {
    "jquery": "^3.6.0" // {1}
  }
}

// package-lock.json
{
  "dependencies": {
    "jquery": {
      "version": "3.6.0", // {2}
      "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.6.0.tgz",
      "integrity": "sha512-JVzAR/AjBvVt2BmYhxRCSYysDsPcssdmTFnzyLEts9qNwmjmu4JTAMYubEfwVOSwpQ1I1sKKFcxhZCI2buerfw=="
    }
  }
}

package-lock.json 最重要的作用是锁定版本。在 package-lock.json 中明确写明 jquery 的版本是 3.6.0,而 package.json 中的是 ^3.6.0。

其次,package-lock.json 能提升下次执行 npm install 的速度。通常一个包会依赖其他很多包(jquery是特列),以 express 为例:

$ npm install express

// package.json
{
  "dependencies": {
    "express": "^4.17.1"
  }
}

// package-lock.json
{
    // dependencies 中的都是 express 依赖的包
    "dependencies": { 
        "accepts": {
            "version": "1.3.7",
            "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
            "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
        },
        "array-flatten": {
            "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
        },
        "body-parser": {
            "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
        },
        ...
        "express": {
            "version": "4.17.1",
            "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz",
            "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==",
            "requires": {
                ...
            }
        }
        ...
        // express 依赖的包还有很多
    }
}

执行 npm install express 花费 12s。因为需要先下载 express,解析 express 中的 package.json,下载里面依赖的包,接着分析依赖包并下载,如此反复执行,所以花费时间较长。而再次运行 npm install,只需找到 package-lock.json 文件,无需循环下载、解析,而是直接从 resolved 指向的地址下载包即可。

npm uninstall

运行 npm uninstall express,会从 package.json 文件、package-lock.json 文件,以及 node_modules 文件夹,这三个方面删除 express 相关的依赖包。

安装(npm install)有保存软件包的位置和方式(--save、--save-dev),卸载(npm uninstall)时也有(--save、--save-dev)。请看示例。

// 最初安装了两个包
{
  ...
  "license": "ISC",
  "dependencies": {
    "jquery": "^3.6.0"
  },
  "devDependencies": {
    "underscore": "^1.12.0"
  }
}

// 卸载 jquery,dependencies 对象被删除
$ npm uninstall jquery
{
  ...
  "license": "ISC",
  "devDependencies": {
    "underscore": "^1.12.0"
  }
}

// 卸载 underscore,devDependencies 对象被删除
$ npm uninstall underscore --save-dev
{
  ...
  "license": "ISC"
}

运行 npm uninstall jquerynpm uninstall jquery --save 的效果相同(npm 以前的版本需要指定 --save)

:如果上面例子中执行 npm uninstall jquery --save-dev,效果与 npm uninstall jquery 类似,也能达到卸载的目的。建议不要这样,如果要删除 devDependencies 中的包,那就使用 --save-dev

npm --help

通过 npm --help 可以查看 npm 命令。请看示例:

$ npm --help

Usage: npm <command>

npm install        install all the dependencies in your project
npm install <foo>  add the <foo> dependency to your project
npm test           run this project's tests
npm run <foo>      run the script named <foo>
npm <command> -h   quick help on <command>
npm -l             display usage info for all commands
npm help <term>    search for help on <term> (in a browser)
npm help npm       more involved overview (in a browser)

All commands:

    access, adduser, audit, bin, bugs, cache, ci, completion,
    config, dedupe, deprecate, diff, dist-tag, docs, doctor,
    edit, exec, explain, explore, find-dupes, fund, get, help,
    hook, init, install, install-ci-test, install-test, link,
    ll, login, logout, ls, org, outdated, owner, pack, ping,
    prefix, profile, prune, publish, rebuild, repo, restart,
    root, run-script, search, set, set-script, shrinkwrap, star,
    stars, start, stop, team, test, token, uninstall, unpublish,
    unstar, update, version, view, whoami

如果需要查看特定命令的帮助,可以使用 npm 命令 --help。例如:

$ npm init --help

npm init [--force|-f|--yes|-y|--scope]
npm init <@scope> (same as `npx <@scope>/create`)
npm init [<@scope>/]<name> (same as `npx [<@scope>/]create-<name>`)

aliases: create, innit

有快速创建 package.json 的参数 -y

$ npm install --help
npm install (with no args, in package dir)
npm install [<@scope>/]<pkg>
npm install [<@scope>/]<pkg>@<tag>
npm install [<@scope>/]<pkg>@<version>
npm install [<@scope>/]<pkg>@<version range>
npm install <alias>@npm:<name>
npm install <folder>
npm install <tarball file>
npm install <tarball url>
npm install <git:// url>
npm install <github username>/<github project>

aliases: i, in, ins, inst, insta, instal, isnt, isnta, isntal, add
common options: [--save-prod|--save-dev|--save-optional|--save-peer] [--save-exact] [--no-save]

可以使用 install 的别名,例如要安装 jquery:npm i jquery

npm 镜像

由于 npm 的服务器是国外的,下载包有时会很慢,所以我们有时会配置镜像。比如配置淘宝镜像,使用起来也很方便,用 cnpm 代替 npm。例如要通过镜像下载: cnpm install jquery

发布一个 npm 包

前面我们已经知道,就是提供给他人使用的项目,可以是简单的几行代码。所以下面笔者就创建一个项目,将其发布到 npm。

创建项目

首先通过 npm init -y 初始化项目

// 创建文件夹
$ mkdir a-new-npm
$ cd a-new-npm
$ npm init -y
{
  "name": "a-new-npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

新建入口文件 index.js,内容如下:

$ cat a-new-npm/index.js
export var name = 'ph'
export let age = 18

// 导出函数
export function sum(v1, v2) {
    return v1 + v2
}

发布

首先到 npm 官网进行注册

:输入用户名、密码、邮箱点击注册按钮,提示出现意外,但没有明确提示为什么失败,接着尝试在命令行中注册(npm adduser),提示”在已知泄露密码的公开列表中检测到您输入的密码。 请输入一个不同的密码“,于是换了一个密码就注册成功了。

接着在命令行中登录 a-new-npm> npm login

Tip:登录后好像需要到邮箱中验证一下

最后直接通过 npm publish 发布即可:

a-new-npm> npm publish
npm notice 
npm notice 📦  a-new-npm@1.0.0
npm notice === Tarball Contents ===
npm notice 116B index.js
npm notice 223B package.json
npm notice === Tarball Details ===
npm notice name:          a-new-npm
npm notice version:       1.0.0
npm notice filename:      a-new-npm-1.0.0.tgz
npm notice package size:  379 B
npm notice unpacked size: 339 B
npm notice shasum:        03beea4r5gfe3ef8ff2c9b62004bb9a6c79ee4
npm notice integrity:     sha512-MKedrrgftti4TVU[...]CNY3RzVWCOrJw==
npm notice total files:   2
npm notice
npm ERR! code E403
// 您不能在以前发布的版本上发布:1.0.0。
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/a-new-npm - You cannot publish over the previously published versions: 1.0.0.

由于笔者已经发布,再次执行则会提示:不能在以前发布的版本上发布。

发布后,会收到一封来自 npm 的邮件:

Hi pengjiali!

A new version of the package a-new-npm (1.0.0) was published at 2021-12-13T14:40:34.856Z from...

If you have questions or security concerns, you can contact us at https://www.npmjs.com/support.

npm loves you.

至此,我们就已经将包(a-new-npm) 发布到 npm 中了。

其他章节请看:

前端学习 node 快速入门 系列

posted @ 2021-03-10 19:24  彭加李  阅读(1166)  评论(0编辑  收藏  举报