在vscode集成终端中用node执行js文件报错:ReferenceError: __dirname is not defined in ES module scope
在vscode集成终端中用node执行js文件报错:ReferenceError: __dirname is not defined in ES module scope
·
在vscode集成终端中用node执行js文件报错:
ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\temp\前端\mock-demo\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///D:/temp/%E5%89%8D%E7%AB%AF/mock-demo/mock/testJSON5.js:4:40
at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
at async loadESM (node:internal/process/esm_loader:28:7)
at async handleMainPromise (node:internal/modules/run_main:113:12)
Node.js v20.12.1
原因在package.json文件中配置的是"type": "module"
,js文件作为ES模块对待,而此时__dirname
这个变量没有定义:
修改方法:
用const __dirname = path.resolve()
定义__dirname
,然后再使用。testJSON5.js文件修改后如下:
import fs from 'fs'
import path from 'path'
const __dirname = path.resolve()
const json = fs.readFileSync(path.join(__dirname, './userInfo.json5'), 'utf-8')
console.log(json)
现在运行正常了:
更多推荐
已为社区贡献19条内容
所有评论(0)