在 mjs 文件中,我们需要对__dirname和require等全局变量进行模拟。我们可以借助 fileURLToPath 和 createRequire 来进行模拟,具体实现如下:
// temp.mjsimport { createRequire } from 'module'import { dirname } from 'path'import { fileURLToPath } from 'url'const _dirname = typeof __dirname !== undefined? __dirname: dirname(fileURLToPath(import.meta.url))const _require = createRequire(import.meta.url)
