node运行文件报错,ReferenceError: __dirname is not defined

1,380 阅读1分钟

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

注解: node中文网未更新,node官网是有说明的,ES不支持require, exports, module.exports, __filename, __dirname

package.json 加了以下配置

"type": "module",

解决

1、方法一

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

2、方法二

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

const __dirname = path.resolve();

console.log(__dirname);

2.推荐

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