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

如何使用ts-morph实现'require'到'import'的程序化转换?

程序化将 require 转换为 import 的实现方案

方案一:使用 ts-morph

ts-morph 可以直接调用 TypeScript 的代码修复能力,或是用内置方法批量转换:

方式1:基于代码修复API

import { Project } from "ts-morph";

const project = new Project({
  tsConfigFilePath: "./tsconfig.json",
});

// 遍历项目中的所有源文件
const sourceFiles = project.getSourceFiles();
for (const sourceFile of sourceFiles) {
  // 获取当前文件的所有诊断及对应修复方案
  const fixes = await sourceFile.getCodeFixesForDiagnostics([
    ...sourceFile.getDiagnostics(),
  ]);

  // 筛选出「将require转换为import」的修复项
  const convertFixes = fixes.filter(fix => fix.description.includes("Convert 'require' to 'import'"));

  // 应用所有符合条件的修复
  for (const fix of convertFixes) {
    await fix.apply();
  }
}

// 保存所有修改
await project.save();

方式2:使用内置转换方法

如果你的 ts-morph 版本支持,可直接调用convertCommonJSToESModules方法一键转换:

import { Project } from "ts-morph";

const project = new Project({
  tsConfigFilePath: "./tsconfig.json",
});

const sourceFiles = project.getSourceFiles();
for (const sourceFile of sourceFiles) {
  sourceFile.convertCommonJSToESModules();
}

await project.save();

方案二:使用 typescript-language-server

通过 Language Server Protocol(LSP)调用代码动作,流程如下:

import { LanguageClient, TransportKind } from "vscode-languageclient/node";
import * as path from "path";
import * as fs from "fs";

// 初始化语言客户端,连接typescript-language-server
const serverModule = path.join(
  __dirname,
  "..",
  "node_modules",
  "typescript-language-server",
  "lib",
  "cli.js"
);

const client = new LanguageClient(
  "typescript-language-server",
  "TypeScript Language Server",
  {
    run: { module: serverModule, transport: TransportKind.ipc },
    debug: { module: serverModule, transport: TransportKind.ipc },
  },
  {
    documentSelector: [{ scheme: "file", language: "typescript" }],
  }
);

// 启动客户端
await client.start();

// 目标文件路径(替换为你的文件路径)
const filePath = "/path/to/your/target-file.ts";
const fileUri = `file://${filePath}`;
const fileContent = fs.readFileSync(filePath, "utf-8");

// 通知服务器打开目标文件
await client.sendNotification("textDocument/didOpen", {
  textDocument: {
    uri: fileUri,
    languageId: "typescript",
    version: 1,
    text: fileContent,
  },
});

// 获取文件的诊断信息
const diagnostics = await client.sendRequest("textDocument/diagnostic", {
  textDocument: { uri: fileUri },
});

// 遍历诊断,筛选并应用转换代码动作
for (const diagnostic of diagnostics) {
  const codeActions = await client.sendRequest("textDocument/codeAction", {
    textDocument: { uri: fileUri },
    range: diagnostic.range,
    context: { diagnostics: [diagnostic] },
  });

  // 找到「将require转换为import」的动作
  const convertAction = codeActions.find(
    action => action.title.includes("Convert 'require' to 'import'")
  );

  // 应用编辑
  if (convertAction?.edit) {
    await client.sendRequest("workspace/applyEdit", { edit: convertAction.edit });
  }
}

// 保存修改后的文件
await client.sendNotification("textDocument/didSave", { textDocument: { uri: fileUri } });

// 停止客户端
await client.stop();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:13:24