在EsModule规范下使用__dirname

520 阅读1分钟

__dirname 仅能在 commonjs 模式下使用. 在 EsModule 模式下直接使用会抛异常:ReferenceError: __dirname is not defined in ES module scope

ReferenceError: __dirname is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and 'D:\_各种练习\前端工程化\重复的肌肉记忆_rollup\rr1\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

使用以下固定写法.在EsModule模式下自建一个 __dirname

import path, { dirname } from "path"
import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url));

--- 完 ---