ESM 中 __dirname/__filename 兼容方案

33 阅读1分钟

定义

// src/esm-dirname.js (ESM 模块)  
import { fileURLToPath } from 'url';  
import { dirname, join } from 'path';

// 1. 实现 __filename 替代  
const __filename = fileURLToPath(import.meta.url);  
// 2. 实现 __dirname 替代  
const __dirname = dirname(__filename);

// 测试:拼接路径  
const utilsPath = join(__dirname, './utils/index.js');

console.log('===== ESM 路径兼容 =====');  
console.log('ESM __filename:', __filename);  
console.log('ESM __dirname:', __dirname);  
console.log('拼接后的 utils 路径:', utilsPath);

// 导出工具函数,供其他模块使用  
export { __filename, __dirname };

使用

// src/esm-module.js 中使用
import { __dirname, __filename } from './esm-dirname.js';

console.log('\n===== 外部模块使用路径兼容 =====');
console.log('主模块 __dirname:', __dirname);