目录作为模块


可以通过三种方式将文件夹作为参数传给 require()

首先是在文件夹的根目录创建 package.json 文件,指定 main 模块。 一个示例 package.json 文件可能如下所示:

{ "name" : "some-library",
  "main" : "./lib/some-library.js" }

如果这是在 ./some-library 的文件夹中,则 require('./some-library') 将尝试加载 ./some-library/lib/some-library.js

如果目录中不存在 package.json 文件,或者 "main" 条目丢失或无法解析,则 Node.js 将尝试从该目录中加载 index.jsindex.node 文件。 例如,如果前面的示例中没有 package.json 文件,则 require('./some-library') 将尝试加载:

  • ./some-library/index.js
  • ./some-library/index.node

如果这些尝试失败,Node.js 将报告整个模块丢失,并显示默认错误:

Error: Cannot find module 'some-library'

在上述所有三种情况下,import('./some-library') 调用都将导致 ERR_UNSUPPORTED_DIR_IMPORT 错误。 使用包子路径导出子路径导入可以提供与文件夹作为模块相同的包含组织优势,并且适用于 requireimport

Stability: 3 - Legacy: Use subpath exports or subpath imports instead.

There are three ways in which a folder may be passed to require() as an argument.

The first is to create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:

{ "name" : "some-library",
  "main" : "./lib/some-library.js" }

If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js.

If there is no package.json file present in the directory, or if the "main" entry is missing or cannot be resolved, then Node.js will attempt to load an index.js or index.node file out of that directory. For example, if there was no package.json file in the previous example, then require('./some-library') would attempt to load:

  • ./some-library/index.js
  • ./some-library/index.node

If these attempts fail, then Node.js will report the entire module as missing with the default error:

Error: Cannot find module 'some-library'

In all three above cases, an import('./some-library') call would result in a ERR_UNSUPPORTED_DIR_IMPORT error. Using package subpath exports or subpath imports can provide the same containment organization benefits as folders as modules, and work for both require and import.