小龙虾学习基础知识7. createRequire 用法教程

1 阅读1分钟

二、createRequire 详解

为什么需要它

本项目使用 ESM("module": "NodeNext"),ESM 原生没有 require()。虽然 Node.js 提供了 import assertion 语法来导入 JSON:

import pkg from "../package.json" with { type: "json" };

但该语法较新,兼容性不如 createRequire 方案稳定。因此项目选择 createRequire 来实现同步 JSON 加载。

用法

import { createRequire } from "node:module";

// import.meta.url 提供当前模块的文件路径,用于解析相对路径
const require = createRequire(import.meta.url);

// 等价于 CommonJS 中的 require(),同步读取 JSON 文件
const pkg = require("../package.json") as { version?: string };

核心要点

特性说明
来源node:module 内置模块
参数import.meta.url(当前模块的 URL,用于解析相对路径)
返回值一个功能等同 CJS require 的函数
适用场景ESM 中需要同步 require() JSON 或 CJS 模块

与其他方案的对比

方案优点缺点
createRequire兼容性好,同步加载,写法简单引入了 CJS 兼容层
import assertion (with { type: "json" })原生 ESM,无 CJS 依赖需要 Node ≥ 22 稳定支持
fs.readFileSync + JSON.parse无需特殊 API需要手动拼接路径,类型断言更繁琐

三、导出接口

/** 当前 CLAWDIS 版本,派生自 package.json。缺失时回退为 "0.0.0"。 */
export const VERSION: string;
  • 读取 package.jsonversion 字段
  • 若字段缺失,回退为 "0.0.0"