文件夹作为模块


【Folders as modules】

稳定性: 3 - 传统做法:请使用 子路径导出子路径导入

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

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

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

【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" } 

如果这个文件在 ./some-library 文件夹中,那么 require('./some-library') 会尝试加载 ./some-library/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.】

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

【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

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

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

Error: Cannot find module 'some-library' 

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

【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.】