在esm中优雅的使用__dirname

在esm中没有这些 __dirname、require,因为这是cjs的规范。
但是通过如下代码,你即可使用上

import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";

// 定义一个全局变量 __dirname
let dirnameVal = '';
Object.defineProperty(global, "__dirname", {
  get() {
    // ---这段代码不能提出去---
    const stackLines = new Error().stack.split("\n");
    const callerLine = stackLines[2];
    const [_, callerFilePath] = callerLine.match(/\(([^)]*)\)/);

    // --- 返回出去 ---
    return path.dirname(fileURLToPath(callerFilePath));
  },
  set(value) {
    dirnameVal = value;
  },
});

global.require = (path) => { // 需要注意的是 只能使用它来引入cjs或json
  // ---这段代码不能提出去---
  const stackLines = new Error().stack.split("\n");
  const callerLine = stackLines[2];
  const [_, callerFilePath] = callerLine.match(/\(([^)]*)\)/);
  const trequire = createRequire(callerFilePath);
  return trequire(path);
};
posted @   丁少华  阅读(61)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示