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

如何在Visual Studio Code扩展中正确使用get-port包?

解决VS Code扩展中使用get-port的模块加载错误

这个问题我之前也碰到过!核心原因是get-port从某个版本开始完全转为了ES模块(ESM),而VS Code的扩展宿主环境目前还是默认使用CommonJS模块系统来加载扩展代码的,两者的模块系统不兼容,才出现了require() of ES Module的报错。下面给你一步步的解决方法:

1. 调整TypeScript配置,适配CommonJS环境

首先把你的tsconfig.json调整为CommonJS编译格式,同时开启ES模块互支持的选项:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES2020",
    "outDir": "out",
    "lib": ["ES2020"],
    "sourceMap": true,
    " "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
  • esModuleInterop和allowSyntheticDefaultImports这两个选项能让TypeScript更好地处理ES模块的导入,避免CommonJS和ESM之间的适配问题。

2. 使用动态导入加载get-port

因为get-port本身是ESM,即使调整了TS配置,静态导入还是可能触发加载错误,所以我们改用**动态导入(import())**的方式异步加载它:

import * as vscode from 'vscode';

export async function activate(context: vscode.ExtensionContext) {
  const viewPortCommand = vscode.commands.registerCommand('vscode-test-getport.viewPort', async () => {
    // 动态导入get-port,注意取default导出
    const getPort = (await import('get-port')).default;
    const availablePort = await getPort();
    vscode.window.showInformationMessage(`可用端口:${availablePort}`);
  });

  context.subscriptions.push(viewPortCommand);
}

export function deactivate() {}

动态导入是CommonJS模块中加载ESM的标准方式,能避开require()直接加载ESM的限制。

3. 确保package.json的模块类型正确

不要在你的扩展package.json中设置"type": "module",VS Code扩展需要CommonJS格式的入口文件,保持默认即可(默认就是CommonJS类型),如果之前加过这个配置,记得删掉。

4. 清理并重新编译

  • 删除out目录,避免残留旧的编译文件
  • 重新运行tsc编译代码
  • 打开VS Code命令面板(Ctrl+Shift+P),执行"Reload Window"重启扩展宿主环境

为什么之前的两种配置都失败?

  • 用module: es6的配置:编译后的代码是ES模块,但VS Code的扩展加载器用require()来加载扩展入口,CommonJS的require()无法直接加载ES模块,所以报错。
  • 用默认CommonJS配置但没处理ESM依赖:get-port本身是ESM,静态导入时会触发require()加载ESM的错误,因为CommonJS规范不支持直接require ES模块。

内容的提问来源于stack exchange,提问作者Håkon Høgland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 18:37:27