一旦你在 node_modules 中有 安装了一个包,你就可以在你的代码中使用它。

¥Once you have installed a package in node_modules, you can use it in your code.

在项目中使用无范围的包

¥Using unscoped packages in your projects

Node.js 模块

¥Node.js module

如果你正在创建 Node.js 模块,则可以通过将包作为参数传递给 require 函数来使用模块中的包。

¥If you are creating a Node.js module, you can use a package in your module by passing it as an argument to the require function.

var lodash = require('lodash');
var output = lodash.without([1, 2, 3], 1);
console.log(output);

package.json 文件

¥package.json file

package.json 中,列出依赖下的包。你可以选择包含 语义版本

¥In package.json, list the package under dependencies. You can optionally include a semantic version.

{
"dependencies": {
"package_name": "^1.0.0"
}
}

在项目中使用范围包

¥Using scoped packages in your projects

要使用范围包,只需在使用包名称的任何位置包含范围即可。

¥To use a scoped package, simply include the scope wherever you use the package name.

Node.js 模块

¥Node.js module

var projectName = require("@scope/package-name")

package.json 文件

¥package.json file

package.json

¥In package.json:

{
"dependencies": {
"@scope/package_name": "^1.0.0"
}
}

解决 "找不到模块" 错误

¥Resolving "Cannot find module" errors

如果你没有正确安装包,当你尝试在代码中使用它时会收到错误消息。例如,如果你引用 lodash 包而不安装它,你会看到以下错误:

¥If you have not properly installed a package, you will receive an error when you try to use it in your code. For example, if you reference the lodash package without installing it, you would see the following error:

module.js:340
throw err;
^
Error: Cannot find module 'lodash'
  • 对于范围包,运行 npm install <@scope/package_name>

    ¥For scoped packages, run npm install <@scope/package_name>

  • 对于无范围的包,运行 npm install <package_name>

    ¥For unscoped packages, run npm install <package_name>

npm 中文网 - 粤ICP备13048890号