Skip to content

node运行报错, __dirname is not defined

原因,NodeJS 支持通过 ESM 方式导入模块

当在package.json中设置了"type":"module"后,开启ES模块化,就不能直接使用__dirname了,这是因为ES不支持require, exports, module.exports, __filename, __dirname

解决

1、方法一

删除文件 package.json 中的配置项:"type": "module"

2、方法二

  1. 这种存在一些问题,特别是脚手架使用path.resolve(__dirname, './cmds')这种路径就会不是脚手架目录路径,是当前命令行启动程序的路径。
javascript
import path from "path"

const __dirname = path.resolve();

console.log(__dirname);
import path from "path"

const __dirname = path.resolve();

console.log(__dirname);

2.推荐

javascript
import { fileURLToPath } from 'url'
import { dirname } from 'path'
 const __filename = fileURLToPath(import.meta.url)
 const __dirname = dirname(__filename)
 console.log(__filename)
 console.log(__dirname)
import { fileURLToPath } from 'url'
import { dirname } from 'path'
 const __filename = fileURLToPath(import.meta.url)
 const __dirname = dirname(__filename)
 console.log(__filename)
 console.log(__dirname)