目录

一旦你在 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>
  • 对于无作用域的包,运行 npm install <package_name>

目录