__dirname is not defined in ES module scope
·
__dirname是commonjs规范的内置变量。如果使用了esm,是不会注入这个变量的。
在commonjs中,注入了__dirname,__filename, module, exports, require五个内置变量用于实现导入导出的能力。而在esm中,因为规范已经完全不一样,故实现方式也是不一样的。
在esm中,显然模块的导入导出使用export/import,自然不会再用exports /require,同理__dirname,__filename也有对应的规范写法。
import path from 'path';
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
可以看到使用了一个关键API import.meta.url,其实import.meta是ECMA规范的一部分:
The import.meta object exposes context-specific metadata to a JavaScript module. It contains information about the module, like the module’s URL.
如上,言下之意,import.meta提供了一个模块的上下文信息,其实上文commonjs的提供的那些变量不也是上下文信息么?只不过标准不一样了,写法也不一样了。
更多推荐



所有评论(0)