如果要使用 ES 模块而不是 CommonJS 模块构建 Node.js 应用程序,可以通过使用.mjs或者在package.json中添加"type": "module",这样就可以使用ESM了。需要注意的是在ESM中使用__filename和__direname之前有些不一样。
问题在使用ESM构建 Node.js 应用程序的时候,如果程序中用到了__filename和__direname,则会遇到以下错误:
ReferenceError: __dirname is not defined in ES module scope
和:
ReferenceError: __filename is not defined in ES module scope
可以通过以下的解决方案来处理。
解决方案以下是解决问题的方法:
import url from "url";
import path from "path";
const getPath = (url2) => {
console.log(process.cwd());
const __filename = url.fileURLToPath(url2);
const __dirname = path.dirname(__filename);
return {__filename,__dirname}
}
const {__filename,__dirname} = getPath(import.meta.url)
console.log(__filename);
console.log(__dirname);
执行上述代码时,您将看到类似于以下内容的输出:
/Users/goodman/Desktop/Dev/node/node_kindacode/src/index.js /Users/goodman/Desktop/Dev/node/node_kindacode/src结论
可以愉快的在 ESM构建的 Node.js 中使用 __dirname和__filename



