我正在阅读一个Node.js的cli模块文档,其中有一行代码如下:
const foo = require('.');
我知道我们可以像这样包含外部模块,但不知道在需要模块时为什么要使用'.'。请问有人能告诉我它的用途或为什么要这样使用吗?const foo = require('.');
我知道我们可以像这样包含外部模块,但不知道在需要模块时为什么要使用'.'。请问有人能告诉我它的用途或为什么要这样使用吗?当你在运行文件的文件夹中使用空的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 }
在 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'
index.js
文件。因此,对于 Node 来说,require('.')
相当于require('./index.js')
。 - Francis Leigh