
在给vite+vue3.0设置别名的时候,直接使用了__dirname这个内置变量报错__dirname is not defined in ES module scope
报错原因:
__dirname是commonjs规范的内置变量。如果使用了esm,是不会注入这个变量的。
在commonjs中,注入了__dirname,__filename, module, exports, require五个内置变量用于实现导入导出的能力。而在esm中,因为规范已经完全不一样,故实现方式也是不一样的。
在esm中,显然模块的导入导出使用export/import,自然不会再用exports /require,同理__dirname,__filename也有对应的规范写法。
解决的办法:
import path from 'path'
import { fileURLToPath } from 'url'
const __filenameNew = fileURLToPath(import.meta.url)
const __dirnameNew = path.dirname(__filenameNew)

在Vite+Vue3.0项目中遇到使用__dirname时的错误,原因是__dirname在ES模块中未定义。解决方法是引入path和url库,通过import.meta.url获取当前模块URL并转换为文件路径。具体步骤包括导入path和fileURLToPath,然后利用这些工具来替代__dirname。
4405

被折叠的 条评论
为什么被折叠?



