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

如何在Node.js中直接调用TypeScript的命名导出函数(无需编译保存)

实现动态执行TypeScript命名导出函数的方案

完全可以实现你想要的调用方式,不用再依赖IIFE。下面是具体的实现步骤:

1. 编写自定义执行脚本

创建一个名为ts-executor.ts的文件,用来解析命令行参数、导入目标模块并执行指定函数:

import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { importModule } from 'tsx/esm';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

async function main() {
  const [, , target] = process.argv;
  if (!target) {
    console.error('请指定格式:<file_path>/functionName');
    process.exit(1);
  }

  const [filePath, functionName] = target.split('/');
  if (!filePath || !functionName) {
    console.error('格式错误,请使用:<file_path>/functionName');
    process.exit(1);
  }

  try {
    // 处理相对路径,转换为绝对路径
    const fullPath = join(__dirname, filePath);
    const module = await importModule(fullPath);
    
    if (typeof module[functionName] === 'function') {
      // 支持同步和异步函数
      await module[functionName]();
    } else {
      console.error(`模块中不存在名为 ${functionName} 的导出函数`);
      process.exit(1);
    }
  } catch (err) {
    console.error('执行出错:', err);
    process.exit(1);
  }
}

main();

2. 准备测试用的TypeScript模块

比如创建test.ts,里面包含命名导出的函数:

export function sayHello() {
  console.log('Hello from sayHello!');
}

export async function fetchMockData() {
  console.log('开始模拟获取数据...');
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('模拟数据获取完成!');
}

3. 执行函数的方式

首先确保已经安装了tsx:

npm install -D tsx

然后直接用tsx运行自定义脚本,指定目标文件和函数名:

tsx ts-executor.ts test.ts/sayHello

或者执行异步函数:

tsx ts-executor.ts test.ts/fetchMockData

4. 优化调用体验

可以把执行命令加到package.json的scripts中:

{
  "scripts": {
    "ts-run": "tsx ts-executor.ts"
  }
}

之后调用时只需输入:

npm run ts-run -- test.ts/sayHello

这个方案不需要生成编译后的.js文件,直接通过tsx动态解析并执行指定的命名导出函数,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:25:16