5、npm v3无先决版本

最后更新于:2022-04-02 01:03:07

As stated a few pages back in our example: install order If you, and your development team, use a package.json, as well as the interactive npm install command to add pkgs (like most teams using npm do), it is likely that you will run into a situation where your local node_modules directory will differ from both your coworkers' node_modules directories, as well as the node_modules directories on your staging, testing, or production servers. In short? npm3 does not install dependencies in a deterministic way. That's probably not a comforting statement to read, but in this article we'll discuss why this happens, as well as assure you that it has no implications for your application, as well as explain the steps to reliably (re)create a single, consistent, node_modules directory, should you want to do that. Example Let's jump back to an example application from a few examples ago: app In this example, our app has the following package.json: { "name": "example3", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "mod-a": "^1.0.0", "mod-c": "^1.0.0", "mod-d": "^1.0.0", "mod-e": "^1.0.0" } } On an npm install we will see this in our terminal: npm install Now, let's say a developer on our team decides to complete a feature that requires that they update Module A to v2.0, which now has a dependency on Module B v2.0, instead of, as previously, Module B v1.0. module a v2 Our developer uses the interactive npm install command to install the new version of Module A, and save it to the package.json: npm install mod-a@2 --save The terminal outputs this: interactive install mod a We now have something that looks like this: tree with mod a v2 interactive Now let's say that our developer finished the feature requiring the new version of Module A and pushes the application to a testing server that runs npm install on the new package.json: { "name": "example3", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "mod-a": "^2.0.0", "mod-c": "^1.0.0", "mod-d": "^1.0.0", "mod-e": "^1.0.0" } } The testing server's log shows this: tree with mod a v2 packagejson Which, when visualized, looks like this: totally diff dep tree Whoa, what?! This tree is completely different than the tree that exists on our developer's local machine. What happened? Remember: install order matters. When our developer updated Module A using the interactive npm install Module A v2.0 was functionally the last package installed. Because our developer had done an npm install when they first started working on the project, all modules listed in the package.json were already installed in the node_modules folder. Then Module A v2.0 was installed. It follows, then, that Module Bv1.0, a top level dependency because of Module A v1.0, then anchored by Module E v1.0, remains a top level dependency. Because Module Bv1.0 occupies the top-level, no other version of Module B can-- therefore, Module Bv2.0 remains a nested dependency under Module C v1.0 and Module D v1.0, and becomes a nested dependency for the new Module A v2.0 dependency. Let's consider what happened on the testing server. The project was pulled into a fresh directory, i.e. does not have a pre-existing node_modules directory. Then npm install is run, perhaps by a deploy script, to install dependencies from the package.json. This package.json now has Module A v2.0 listed in it, and thanks to alphabetical order (enforced by the npm install command), is now installed first, instead of last. When Module A v2.0 is installed first, in a clear node_modules directory, its dependencies are the first candidates for the top-level position. As a result, Module B v2.0 is installed in the top-level of the node_modules directory. Now, when it is time to install Module E v1.0, its dependency, Module B v1.0, cannot occupy the top-level of the node_modules directory, because Module B v2.0 is already there. Therefore, it is nested under Module E v1.0. Do different dependency tree structures affect my app? No! Even though the trees are different, both sufficiently install and point all your dependencies at all their dependencies, and so on, down the tree. You still have everything you need, it just happens to be in a different configuration. I want my node_modules directory to be the same. How can I do that? The npm install command, when used exclusively to install packages from a package.json, will always produce the same tree. This is because install order from a package.json is always alphabetical. Same install order means that you will get the same tree. You can reliably get the same dependency tree by removing your node_modules directory and running npm install whenever you make a change to your package.json.
';

4、npm v3副本

最后更新于:2022-04-02 01:03:04

Let's continue with our example before. Currently we have an application that depends on 2 modules: Module-A, depends on Module B v1.0 Module-C, depends on Module B v2.0 our app so far Now we ask ourselves, what happens if we install another module that depends on Module B v1.0? or Module B v2.0? Example Ok, so let's say we want to depend on another package, module D. Module D depends on Module B v2.0, just like Module C. new module dep, D Because B v1.0 is already a top-level dependency, we cannot install B v2.0 as a top level dependency. Therefore Module B v2.0 is installed as a nested dependency of Module D, even though we already have a copy installed, nested beneath Module C. no dedupe If a secondary dependency is required by 2+ modules, but was not installed as a top-level dependency in the directory hierarchy, it will be duplicated and nested beneath the primary dependency. However, if a secondary dependency is required by 2+ modules, but is installed as a top-level dependency in the directory hierarchy, it will not be duplicated, and will be shared by the primary dependencies that require it. For example, let's say we now want to depend on Module E. Module E, like Module A, depends on Module B v1.0. new module dep, E Because B v1.0 is already a top-level dependency, we do not need to duplicate and nest it. We simply install Module E and it shares Module B v1.0 with Module A. dedupe This appears like this in the terminal: tree2 Now-- what happens if we update Module A to v2.0, which depends on Module B v2.0, not Module B v1.0? bump Module A to version 2, deps on Bv2 The key is to remember that install order matters. Even though Module A was installed first (as v1.0) via our package.json (because it is ordered alphabetically), using the interactive npm install command means that Module A v2.0 is the last package installed. As a result, npm3 does the following things when we run npm install mod-a@2 --save: it removes Module A v1.0 it installs Modules A v2.0 it leaves Module Bv1.0 because Module E v1.0 still depends on it it installs Module Bv2.0 as a nested dependency under Module A v2.0, since Module B v1.0 is already occupying the top level in the directory hierarchy bv1.0 stays even though a doesn't dep on it anymore This looks like this in the terminal: tree3 Finally, let's also update Module E to v2.0, which also depends on Module B v2.0 instead of Module B v1.0, just like the Module A update. bump Module E to version 2, deps on Bv2 npm3 performs the following things: it removes Module E v1.0 it installs Module E v2.0 it removes Module B v1.0 because nothing depends on it anymore it installs Module B v2.0 in the top level of the directory because there is no other version of Module B there now we have Bv2.0 everywhere This looks like this in the terminal: tree4 Now, this is clearly not ideal. We have Module B v2.0 in nearly every directory. To get rid of duplication, we can run: npm dedupe This command resolves all of the packages dependencies on Module B v2.0 by redirecting them to the top level copy of Module B v2.0 and removes all the nested copies. deduped This looks like this in the terminal: tree5
';

3、npm v3

最后更新于:2022-04-02 01:03:02

npm3 resolves dependencies differently than npm2. While npm2 installs all dependencies in a nested way, npm3 tries to mitigate the deep trees and redundancy that such nesting causes. npm3 attempts this by installing some secondary dependencies (dependencies of dependencies) in a flat way, in the same directory as the primary dependency that requires it. The key major differences are: position in the directory structure no longer predicts the type (primary, secondary, etc) a dependency is dependency resolution depends on install order, or the order in which things are installed will change the node_modules directory tree structure ## Example - [Explore on Github](https://github.com/ashleygwilliams/npm-sandbox/tree/master/npm3/example1) Imagine we have a module, A. A requires B. A depends on B Now, let's create an application that requires module A. On npm install, npm v3 will install both module A and its dependency, module B, inside the /node_modules directory, flat. In npm v2 this would have happened in a nested way. npm2 vs 3 Now, let's say we want to require another module, C. C requires B, but at another version than A. new module dep, C However, since B v1.0 is already a top-level dep, we cannot install B v2.0 as a top level dependency. npm v3 handles this by defaulting to npm v2 behavior and nesting the new, different, module B version dependency under the module that requires it -- in this case, module C. nested dep In the terminal, this looks like this: tree You can list the dependencies and still see their relationships using npm ls: npmls If you want to just see your primary dependencies, you can use: npm ls --depth=0
';

2、npm v2

最后更新于:2022-04-02 01:03:00

Example - Explore on Github Imagine there are three modules: A, B, and C. A requires B at v1.0, and C also requires B, but at v2.0. We can visualize this like so: 2 modules need B Now, let's create an application that requires both module A and module C. My app needs both A and C Dependency Hell A package manager would need to provide a version of module B. In all other runtimes prior to Node.js, this is what a package manager would try to do. This is dependency hell: Dependency Hell Instead of attempting to resolve module B to a single version, npm puts both versions of module B into the tree, each version nested under the module that requires it. what npm does In the terminal, this looks like this: tree You can list the dependencies and still see their relationships using npm ls: npmls If you want to just see your primary dependencies, you can use: npm ls --depth=0 npmlsdepth0 npm and the Node.js Module Loader However, npm doing this is not enough. Despite the fact that their nested locations allow for the coexistence of two versions of the same module, most module loaders are unable to load two different versions of the same module into memory. Luckily, the Node.js module loader is written for exactly this situation, and can easily load both versions of the module in a way that they do not conflict with each other. How is it that npm and the node module loader are so wonderfully symbiotic? They were both written in large part by the same person, npm, Inc. CEO, Isaac Z. Schlueter. Like 2 sides of the same piece of paper, npm and the Node.js module loader are what make Node.js a uniquely well-suited runtime for dependency management.
';

1、包

最后更新于:2022-04-02 01:02:58

One of the key steps in becoming immersed in an ecosystem is learning its vocabulary. Node.js and npm have very specific definitions of packages and modules, which are easy to mix up. We'll discuss those definitions here, make them distinct, and explain why certain default files are named the way they are. ## tl;dr * A package is a file or directory that is described by a package.json. This can happen in a bunch of different ways! For more info, see "What is a package?, below. * A module is any file or directory that can be loaded by Node.js' require(). Again, there are several configurations that allow this to happen. For more info, see "What is a module?", below. ## What is a package? A package is any of: * a) a folder containing a program described by a package.json file * b) a gzipped tarball containing (a) * c) a url that resolves to (b) * d) a @ that is published on the registry with (c) * e) a @ that points to (d) * f) a that has a latest tag satisfying (e) * g) a git url that, when cloned, results in (a). Noting all these package possibilities, it follows that even if you never publish your package to the public registry, you can still get a lot of benefits of using npm: * if you just want to write a node program, and/or * if you also want to be able to easily install it elsewhere after packing it up into a tarball Git urls can be of the form: ~~~ git://github.com/user/project.git#commit-ish git+ssh://user@hostname:project.git#commit-ish git+http://user@hostname/project/blah.git#commit-ish git+https://user@hostname/project/blah.git#commit-ish ~~~ The commit-ish can be any tag, sha, or branch which can be supplied as an argument to git checkout. The default is master. ## What is a module? A module is anything that can be loaded with require() in a Node.js program. The following are all examples of things that can be loaded as modules: * A folder with a package.json file containing a main field. * A folder with an index.js file in it. * A JavaScript file. ## Most npm packages are modules Generally, npm packages that are used in Node.js program are loaded with require, making them modules. However, there's no requirement that an npm package be a module! Some packages, e.g., cli packages only contain an executable command-line interface, and don't provide a main field for use in Node.js programs. These packages are not modules. Almost all npm packages (at least, those that are Node programs) contain many modules within them (because every file they load with require() is a module). In the context of a Node program, the module is also the thing that was loaded from a file. For example, in the following program: var req = require('request') we might say that "The variable req refers to the request module". ## File and Directory Names in the Node.js and npm Ecosystem So, why is it the node_modules folder, but package.json file? Why not node_packages or module.json? The package.json file defines the package. (See "What is a package?", above.) The node_modules folder is the place Node.js looks for modules. (See "What is a module?", above.) For example, if you create a file at node_modules/foo.js and then had a program that did var f = require('foo.js'), it would load the module. However, foo.js is not a "package" in this case, because it does not have a package.json. Alternatively, if you create a package which does not have an index.js or a "main" field in the package.json file, then it is not a module. Even if it's installed in node_modules, it can't be an argument to require().
';

NPM是如何工作的

最后更新于:2022-04-02 01:02:55

';

15、使用标签

最后更新于:2022-04-02 01:02:53

Tags are a supplement to semver (e.g., v0.12) for organizing and labeling different versions of packages. In addition to being more human-readable, tags allow publishers to distribute their packages more effectively. ## 添加标签(tag) To add a tag to a specific version of your package, use **npm dist-tag add @ []**. See the CLI docs for more information. ## 使用标签(tag)发布 By default, **npm publish** will tag your package with the **latest** tag. If you use the --tag flag, you can specify another tag to use. For example, the following will publish your package with the beta tag: ~~~ npm publish --tag beta ~~~ ## 使用标签(tag)安装 Like npm publish, npm install will use the latest tag by default. To override this behavior, use npm install @. The following example will install the somepkg at the version that has been tagged with beta. ~~~ npm install somepkg@beta ~~~ ## Caveats Because dist-tags share the same namespace with semver, avoid using any tag names that may cause a conflict. The best practice is to avoid using tags beginning with a number or the letter "v".
';

14、使用局部包

最后更新于:2022-04-02 01:02:51

Scopes are like namespaces for npm modules. If a package's name begins with **@**, then it is a scoped package. The scope is everything in between the **@** and the slash. ~~~ @scope/project-name ~~~ Each npm user has their own scope. ~~~ @username/project-name ~~~ You can find more in depth information about scopes in the CLI documentation. ## 更新npm并登录 You need a version of npm greater than 2.7.0, and you'll need to log in to npm again on the command line if this is your first time using scoped modules. ~~~ sudo npm install -g npm npm login ~~~ ## 初始化局部包 To create a scoped package, you simply use a package name that starts with your scope. ~~~ { "name": "@username/project-name" } ~~~ If you use npm init, you can add your scope as an option to that command. ~~~ npm init --scope=username ~~~ If you use the same scope all the time, you will probably want to set this option in your **.npmrc** file. ~~~ npm config set scope username ~~~ ## 发布局部包 Scoped packages are private by default. To publish private modules, you need to be a paid private modules user. However, public scoped modules are free and don't require a paid subscription. To publish a public scoped module, set the access option when publishing it. This option will remain set for all subsequent publishes. ~~~ npm publish --access=public ~~~ ## 使用局部包 To use a scoped package, you simply include the scope wherever you use the package name. In package.json: ~~~ { "dependencies": { "@username/project-name": "^1.0.0" } } ~~~ On the command line: ~~~ npm install @username/project-name --save ~~~ In a require statement: ~~~ var projectName = require("@username/project-name") ~~~ For information about using scoped private modules, visit npmjs.com/private-modules.
';

13、语义化版本号

最后更新于:2022-04-02 01:02:49

> Semantic versioning is a standard that a lot of projects use to communicate what kinds of changes are in this release. It's important to communicate what kinds of changes are in a release because sometimes those changes will break the code that depends on the package. 语义化版本控制是一种标准,许多项目都用它来标识新版本是何种更改。这是非常重要的,因为有时这些更改会破坏依赖这个包的代码。 ## 语义化版本对于发布者 > If a project is going to be shared with others, it should start at **1.0.0**, though some projects on npm don't follow this rule. 如果项目将要与他人分享,那它的版本应该始于**1.0.0**,尽管npm上有些项目不遵循此规则。 > After this, changes should be handled as follows: 之后,所有更改应该按如下方法处理: > Bug fixes and other minor changes: Patch release, increment the last number, e.g. 1.0.1 New features which don't break existing features: Minor release, increment the middle number, e.g. 1.1.0 Changes which break backwards compatibility: Major release, increment the first number, e.g. 2.0.0 * Bug修复和其他小版本修改:用Patch版本,增加最后的版本数,如:1.0.1; * 不会破坏已有特性的新特性:用Minor版本,增加中间的版本数,如:1.1.0; * 会破坏向后兼容的更改:用Majo版本,增加第一个版本数,如:2.0.0. ## 语义化版本对于使用者 > As a consumer, you can specify which kinds of updates your app can accept in the **package.json** file. 如果你是包的使用者,你可以在`package.json`文件中指定你的app能接受哪种版本。 > If you were starting with a package 1.0.4, this is how you would specify the ranges: 如果你用某包的1.0.4版本开始开发的,你可以按下面方式指定版本范围: * 补丁版本(Patch releases): 1.0 or 1.0.x or ~1.0.4 * 次版本(Minor releases): 1 or 1.x or ^1.0.4 * 主版本(Major releases): * or x > You can also specify more granular semver ranges. 你也可以指定更细的语义版本范围。
';

12、发布npm包

最后更新于:2022-04-02 01:02:46

你可以发布任何包含**package.json**文件的目录,比如Nodejs模块。 ## 创建用户 发布包之前,你必须创建一个npm用户账号。如果还没有,你可以用**npm adduser**创建一个。如果已经注册了,使用**npm login**命令将账号信息存储到本地客户端。 测试:使用**npm config ls**确认账号信息已经存储到您的客户端。访问https://npmjs.com/~ 以确保信息正确。 ## 发布包 使用**npm publish**来发布程序包。 > Note that everything in the directory will be included unless it is ignored by a local **.gitignore** or **.npmignore** file as described in **npm-developers**. 注意,目录下的所有文件都将被包含进去,除非目录下有**.gitignore** 或 **.npmignore**文件(详情请看**npm-developers**)将其排除。 > Also make sure there isn't already a package with the same name, owned by somebody else. 同时,请确保npm上没有别的开发者提交的同名都包存在。 > Test: Go to **https://npmjs.com/package/**. You should see the information for your new package. 测试:前往**https://npmjs.com/package/**。你应该可以看到发布的新包的信息了。 ## 更新包 > When you make changes, you can update the package using npm version , where update_type is one of the semantic versioning release types, patch, minor, or major. This command will change the version number in package.json. Note that this will also add a tag with this release number to your git repository if you have one. 当你修改了你的包文件,你可以用`npm version `更新它。update_type是指语义化版本管理的发布类型的一种:补丁版本(patch)、次版本(minor)或主版本(major)。此命令会更改package.json中的版本号。注意哦,如果你有此包的git仓库,那么此命令也会向git仓库添加此版本的一个标签。 > After updating the version number, you can npm publish again. 更新版本号之后,你就可以再次 `npm publish` 了。 > Test: Go to https://npmjs.com/package/. The package number should be updated. 测试:前往 **https://npmjs.com/package/**,包的版本号应该已更新了。 > The README displayed on the site will not be updated unless a new version of your package is published, so you would need to run npm version patch and npm publish to have a documentation fix displayed on the site. 站点下的README文件是不会更新,除非你的包的新版本发布成功。所以你需要运行`npm version patch`和`npm publish`命令来修复站点下的文档。
';

11、创建Node.js模块

最后更新于:2022-04-02 01:02:44

Node.js模块是一种可以发布到npm的包。当你创建一个新模块的时候,你将从 `package.json` 文件开始。 使用 `npm init` 命令创建 `package.json` 文件。命令行中将会弹出package.json字段中要你输入的值。两个必填字段:名称(name)和版本(version)。你可能也需要输入主文件字段(main),可以使用默认值 `index.js`。 如果你想为作者(author)字段添加信息,你可以使用以下格式(邮箱、网站都是选填的): ~~~ Your Name (http://example.com) ~~~ 一旦`package.json`文件创建好了,你将想要创建模块的入口文件,如果使用默认值,他将会是 `index.js`。 在此文件中,添加一个函数,作为 `exports` 对象的一个属性。这样,require此文件之后,这个函数在其他代码中就可以使用了。 ~~~ exports.printMsg = function() { console.log("This is a message from the demo package"); } ~~~ 测试: 1. 将你的包发布到npm 2. 在你的项目外新建一个目录,然后 `cd` 过去 3. 运行 `npm install ` 4. 创建一个test.js文件,require这个包,并调用此方法(函数) 5. 运行 node test.js。终端将会输出:This is a message from the demo package 恭喜你,你的第一个npm包创建成功了。
';

10、卸载全局包

最后更新于:2022-04-02 01:02:42

卸载全局包使用 `npm uninstall -g ` 命令: ~~~ npm uninstall -g jshint ~~~
';

9、更新全局包

最后更新于:2022-04-02 01:02:39

要更新全局包的话,那就再全局安装一下:`npm install -g `: ~~~ npm install -g jshint ~~~ 如果想要找出哪些包需要更新,你可以使用 `npm outdated -g --depth=0` 命令帮忙。 > **译注:** > * 有时候,在项目文件夹中直接 `npm install`,通过package.json的依赖声明中重新安装所有包,给人感觉挺Low B的。这个时候就需要找出哪些包已经过时了,需要更新。 > * 而且,有时候有些依赖包没被声明在package.json文件中,那npm install就对他不起作用了。 > * `--depth=0` 的意思是依赖包的深度,只检查顶层依赖包。 更新所有全局包,你可以使用 `npm update -g`。(译注:这可能会很慢,因为你装了太多依赖了) 注意:npm版本低于2.6.1的话,此命令被建议用来更新所有过时的全局包。
';

8、全局安装npm包

最后更新于:2022-04-02 01:02:37

安装npm包有两种方法:本地安装和全局安装。如何选择安装方式取决于你想如何使用这些依赖包。 > 译注:所谓“本地安装”,就是在项目文件夹中安装npm依赖包,以便此项目调用;“全局安装”相反,安装之后可以供所有项目直接调用,可以免去重复安装的步骤和空间。 如果你期望将包当作命令行工具来使用,比如grunt命令行工具,那你就需要全局安装。 相反地,如果你期望在你自己的模块中引入依赖包,比如用Node的 `require` 方法,那么你需要将它本地安装。 要全局下载依赖包的话,添加-g标识符就好了哦,`npm install -g `,像下面这样: ~~~ npm install -g jshint ~~~ 如果出现EACCES错误,你就修复一下权限。逼不得已的时候,你也可以试试 **sudo**: ~~~ sudo npm install -g jshint ~~~
';

7、卸载本地包

最后更新于:2022-04-02 01:02:35

通过`npm uninstall `命令,你可以将node_modules目录下的某个依赖包移除: ~~~ npm uninstall lodash ~~~ 要从package.json文件的依赖列表中移除,你需要使用`--save`标签: ~~~ npm uninstall --save lodash ~~~ 注意:如果你是以开发依赖包(devDependency)的方式安装的(即安装时待`--dave -dev`标签),那用`--save`将无法从package.json中移除,你必须用`--save -dev`标签。
';

6、更新本地包

最后更新于:2022-04-02 01:02:33

很多时候,你需要升级项目中的依赖包,以获得上游源代码的更新。 运在package.json同级目录下,运行`npm update`命令,来实现依赖包的更新。 测试:运行npm outdated命令,应该不会有什么结果。
';

5、使用package.json配置文件

最后更新于:2022-04-02 01:02:30

管理本地安装的包的最好方法是创建一个package.json文件。 package.json文件会给你提供很多好东西: 1. 它用作你的项目的包依赖管理文档。 2. 它允许你使用语义化版本管理规则,指定项目中能使用的包的版本。 3. 使你的构建版本可以重新生成,这意味着你可以更易于与其他开发者分享代码。 ## 需求 最少配置项, package.json 必须包括以下几项: "name" * 全部为小写字母 * 一个单词,无空格 * 允许半角破折号和下划线 "version" * 格式为 x.x.x * 遵循语义化版本号规则 (semver spec)[https://docs.npmjs.com/getting-started/semantic-versioning] 示例: ~~~ { "name": "my-awesome-package", "version": "1.0.0" } ~~~ ## 创建package.json文件 要创建package.json文件,运行以下命令: ~~~ > npm init ~~~ 此为初始化项目命令,会在你运行此命令的文件夹根目录下创建项目配置文件:package.json。同时每行会出现一个问题,你输入答案后会出来另一个问题。这些问题最终会记录到package.json文件中。 ### “--yes”标签 扩展的命令行问答式流程不是必须的。通常你可以轻松地使用package.json文件快速配置项目。 你可以运行带`--yes`或`-y`标签的`npm init`命令,来生成默认的package.json文件: ~~~ > npm init --yes ~~~ 这样只会问你作者是谁。其他的问题都是用默认值填充的: ~~~ > npm init --yes ~~~ 写入`/home/ag_dubs/my_package/package.json`文件的内容如下: ~~~ { "name": "my_package", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "ag_dubs", "license": "ISC", "repository": { "type": "git", "url": "https://github.com/ashleygwilliams/my_package.git" }, "bugs": { "url": "https://github.com/ashleygwilliams/my_package/issues" }, "homepage": "https://github.com/ashleygwilliams/my_package" } ~~~ * name:默认为作者名字,除非在git目录中,它会是git仓库的名字; * version:版本号,刚初始化的项目总是1.0.0; * main:总是index.js; * scripts:默认创建一行空的测试脚本; * keywords:为空 * author:作者 * license:ISC开源证书 * repository: will pull in info from the current directory, if present * bugs: will pull in info from the current directory, if present * homepage: will pull in info from the current directory, if present 你也可以通过`set`命令来设置一些配置项。比如下边的这些: ~~~ > npm set init.author.email "wombat@npmjs.com" > npm set init.author.name "ag_dubs" > npm set init.license "MIT" ~~~ 注释: If there is no description field in the package.json, npm uses the first line of the README.md or README instead. The description helps people find your package on npm search, so it's definitely useful to make a custom description in the package.json to make your package more discoverable. ## 指定依赖包 To specify the packages your project depends on, you need to list the packages you'd like to use in your package.json file. There are 2 types of packages you can list: * "dependencies": these packages are required by your application in production * "devDependencies": these packages are only needed for development and testing ## 手动编辑package.json You can manually edit your package.json. You'll need to create an attribute in the package object called dependencies that points to an object. This object will hold attributes named after the packages you'd like to use, that point to a semver expression that specifies what versions of that project are compatible with your project. If you have dependencies you only need to use during local development, you will follow the same instructions as above but in an attribute called devDependencies. For example: The project below uses any version of the package my_dep that matches major version 1 in production, and requires any version of the package my_test_framework that matches major version 3, but only for development: ~~~ { "name": "my_package", "version": "1.0.0", "dependencies": { "my_dep": "^1.0.0" }, "devDependencies" : { "my_test_framework": "^3.1.0" } } ~~~ ## `--save` 和 `--save-dev`安装标记 The easier (and more awesome) way to add dependencies to your package.json is to do so from the command line, flagging the npm install command with either --save or --save-dev, depending on how you'd like to use that dependency. 在命令行中使用这两个标记,是添加依赖到你的package.json文件的更简单(也更酷)的方式。 添加package.json依赖的入口: `npm install --save` 添加package.json开发环境依赖的入口: `npm install --save-dev` ## 管理依赖包的版本 npm使用语义化版本管理依赖包,也就是我们常说的“SemVer”。 如果在项目文件夹下有`package.json`文件,你在此文件夹下运行命令`npm install`,npm就会检查文件中列出的依赖包,并下载所有满足语义化规则的最新版本的依赖包。 要学习更多关于语义化版本管理的内容,请查看本章第13节——语义化版本号。
';

4、本地安装npm包

最后更新于:2022-04-02 01:02:28

安装npm包有两种方式:本地安装或全局安装。根据你想如何使用包,你可以选择安装方式。 如果你想要从你自己的模块中通过使用Node.js的require方法来依赖某个包,那你可以本地安装这个包,这是npm安装的默认行为。另外,如果你想当做命令行工具使用它,比如grunt CLI,那你应该全局安这个包。 要学习更多关于安装命令的行为,请查看CLI文档页面。 ## 安装 包可以用以下命令下载: ~~~ > npm install ~~~ 此命令将在你的当前目录创建node_modules目录(若还未安装任何包),并将下载此包到这个目录。 测试 为确保npm安装正确工作,请检查node_modules目录是否存在,以及其下是否包含你安装的包 目录。你可以在Unix系统(如OSX、Debian)中执行“ls node_modules”命令或在Windows系统中执行“dir node_modules”命令来检查。 例子: 安装一个叫“lodash”的包。通过列出node_modules目录内容,看看其中是否存在一个叫“lodash”的目录,来确认成功执行命令。 ~~~ > npm install lodash > ls node_modules # windows中使用 `dir` #=> lodash ~~~ ## 安装的是哪个版本的包? 如果在本地目录中没有package.json文件,那该包的最新版本会被安装了。 如果有package.json文件,那么在package.json中声明的满足semver(语义化版本)规则的最新版本会被安装。 ## 使用已安装的包 一旦包被安装在node_modules,你就可以在你的代码中使用它了。比如,当你创建Node.js模块是,你可以引入它。 示例: 创建名为index.js的文件,其中的代码如下: ~~~ // index.js var lodash = require('lodash'); var output = lodash.without([1, 2, 3], 1); console.log(output); ~~~ 运行命令“node index.js”。终端将输出[2, 3]. 如果你没有正确安装lodash,你将收到如下错误: ~~~ module.js:340 throw err; ^ Error: Cannot find module 'lodash' ~~~ 解决方法:cd到index.js同级目录,运行“npm install lodash”命令。
';

3、处理npm权限问题

最后更新于:2022-04-02 01:02:26

当尝试全局安装某个包得时候,你可能会收到EACCES错误。这说明你没有权限写入npm用于存储全局包和命令的目录。 你可以用下面三种方法解决此问题: 1. 修改npm默认目录的权限; 2. 将npm默认目录定向到其他你具有读写权限的目录; 3. 使用某个包管理器来安装node,它会为你处理好权限问题。 继续下一步之前,你最好先备份以下你的电脑。 ## 方法1:修改npm默认目录的权限 1、找到npm的目录路径: ~~~ npm config get prefix ~~~ 对于很对系统,路径将会是 /usr/local. 警告:如果出来的路径仅是 /usr,请调到方法2,否则你可能会设置错误。 2、将npm目录的拥有者修改为当前用户的名字(你账户的用户名): ~~~ sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share} ~~~ 这会改变npm及其他工具用到的子文件夹的权限(lib/node_modules, bin, and share)。 ## 方法2:将npm默认目录定向到其他你具有读写权限的目录 很多时候你可能并不想改变npm所用的默认目录(如/usr)的拥有者,因为这可能会导致一些问题,比如你在与其他用户共用此系统时。 这时,你可以设置npm整个地去使用另一个目录。我将它设置为我的主文件夹下的一个隐藏的目录。 1、创建一个目录用作全局安装: ~~~ mkdir ~/.npm-global ~~~ 2、配置npm使用这个新目录: ~~~ npm config set prefix '~/.npm-global' ~~~ 3、打开或者创建一个“~/.profile”文件并添加下行代码: ~~~ export PATH=~/.npm-global/bin:$PATH ~~~ 4、返回命令行,更新系统变量: ~~~ source ~/.profile ~~~ 测试:不用sudo,全局下载安装一个包: ~~~ npm install -g jshint ~~~ 不使用第2-4步的方法的话,你也可以使用相应的环境变量(比如如果你不想编辑~/.profile)来实现: ~~~ NPM_CONFIG_PREFIX=~/.npm-global ~~~ ## 方法3:使用某个包管理器来为你解决权限问题。 如果你正在Mac OS上全新安装node,你可以使用Homebrew包管理器,避免所有的问题。Homebrew使用正确的权限设置它安装的程序来填坑。(Homebrew真的很“自酿”……) ~~~ brew install node ~~~ --
';

2、安装Node.js和更新npm

最后更新于:2022-04-02 01:02:24

## 安装Node.js 如果你使用的时OS X或Windows,安装Node.js的最好方法就是使用Node.js下载页面的安装包。如果你使用的时Linux系统,你可以使用安装包,也可以查看NodeSource上的二进包,看看是否有最近版本可以用于你的系统。 测试:运行指令 **node -v**。版本号应该高于v0.10.32(我用的是5.6.0). ## 更新npm Node自带npm,所以装完应该会有某个版本的npm。但npm相比Node更新更频繁,所以,要是想确保使用的是最新版本的,你可以执行以下命令: ~~~ npm install npm -g ~~~ 测试:运行指令 **npm -v**。版本号应该高于2.1.8(我用的是3.10.6)。 ## 手动安装npm 针对更多高级用户 npm模块可供下载的地址:https://registry.npmjs.org/npm/-/npm-{VERSION}.tgz。 (请将“**{VERSION}**”替换成**版本号**)
';