You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用tsx运行含endent等标签模板字面量的代码?

使用tsx运行endent模板字符串时报错TypeError: endent is not a function

问题详情

执行命令 npx tsx test.ts 运行以下代码时:

// test.ts
import endent from 'endent';

const stringProcessor = (str: TemplateStringsArray) => {
  return `  ${str.join()}`;
};

function main() {
  // console.log(stringProcessor`test`); // 此代码可正常运行
  console.log(endent`test`); // 此代码执行失败
}

main();

出现如下错误:

TypeError: endent is not a function
    at main (test.ts:9:15)
    at <anonymous> (test.ts:12:1)
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:323:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/process/esm_loader:28:7)

系统环境:

  • MacOS: 14.2.1 (Arm)
  • tsx: v4.7.2
  • node: v21.7.1

请问是否可通过配置解决该问题,或是tsx存在Bug?

解决方案

这不是tsx的Bug,而是模块导出格式的兼容性问题,可通过调整导入方式解决:

方法1:使用命名导入

将导入语句改为命名导入,直接获取函数:

import { endent } from 'endent';

方法2:手动获取默认导出

如果坚持使用默认导入,需要手动提取模块的default属性:

import endentModule from 'endent';
const endent = endentModule.default;

原因说明

endent包本质是CommonJS格式,在ESM环境下导入时,tsx的模块解析没有自动将module.exports映射为ESM的默认导出,导致直接导入的endent是一个包含default属性的模块对象,而非函数本身。调整导入方式后即可正确获取到模板字符串处理函数。

内容的提问来源于stack exchange,提问作者Nikolay Tsenkov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:30:02