在 Vite 中,默认情况下无法使用'__dirname'变量,因为 Vite 是一个开发服务器和构建工具,而不是 Node.js 运行时。它通常在 Node.js 环境中用于获取当前目录路径。

要解决'Cannot find name '__dirname'' 错误,可以使用'import.meta.url'属性。以下是一个示例:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

console.log(__dirname);

这段代码使用'url'模块中的'fileURLToPath'函数将'import.meta.url'转换为文件路径,然后使用'path'模块中的'dirname'函数提取目录名称。

请注意,'import.meta.url'返回当前模块的 URL,因此需要将其转换为文件路径才能获取目录名称。

确保导入所需的模块('url'和'path')并在项目中使用正确的文件路径。

Vite Vue: 解决'Cannot find name '__dirname'' 错误

原文地址: https://www.cveoy.top/t/topic/paBQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录