关于在vite中 node 中不能使用__dirname报错问题

18 阅读1分钟

问题

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

原因

__dirname 仅能在 commonjs 模式下使用;而在 EsModule 模式下直接使用会抛异常:ReferenceError: __dirname is not defined

解决

方法1

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

// 没了module,只能用require引入
const express = require('express')
const path = require('path')

方法2

import path from 'path';
const __dirname = path.resolve()
console.log('----:::',__dirname)