在Node.js中,'require('。')'有什么用途?

8
我正在阅读一个Node.js的cli模块文档,其中有一行代码如下:const foo = require('.');我知道我们可以像这样包含外部模块,但不知道在需要模块时为什么要使用'.'。请问有人能告诉我它的用途或为什么要这样使用吗?

4
可能是Node.js - require empty path的重复问题。 - user5734311
3
当没有提供文件名时,Node JS 假设存在一个 index.js 文件。因此,对于 Node 来说,require('.') 相当于 require('./index.js') - Francis Leigh
2个回答

14

当你在运行文件的文件夹中使用空的require语句,它将导入该文件夹中的index文件。如果在require()参数中仅提供文件夹引用而不指定任何文件名,则JavaScript require模块将尝试查找index.js文件。

基本上它是const foo = require('./index.js');的别名。

index.js

module.exports = 1;

foo.js

const foo = require('.');
console.log({ foo });
如果两个文件在同一个文件夹中,则会打印。
{ foo: 1 }

2

在 require('.') 中,'.'代表当前目录,而 '..' 代表父级目录。

-- parent 
  -- child1
    -- grandchild1
    -- grandchild2
  -- child2

现在,假设您位于child1并且希望从grandchild1或子文件夹内导入文件,则必须从当前位置(“。”)开始到达grandchild位置。

require('./grandchild1/filename')

如果需要从父级目录或当前目录外导入内容,则必须向后跳转,即从父级位置(“..”)开始:

require('../parent/filename') 
// here '..' take you one folder back (parent folder) and if you want to go one more folder back (parent of parent folder) then add one more pair of dots : '../../some_folder'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接