node __dirname is not defined in ES module scope in JS

es模块中使用__dirname时,会报错

The "__dirname is not defined in ES module scope" error occurs when we try to try to use the __dirname global variable in an ES module file. The __dirname or __filename global variables are not available in ECMAScript module files

解决方案:

import path from 'path';
import {fileURLToPath} from 'url';

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

console.log(path.join(__dirname, 'app'))
posted @ 2022-11-17 17:55  小菜菜爱吃菜  阅读(334)  评论(0编辑  收藏  举报