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

运行VS Code扩展示例时遇‘Cannot find module 'vscode'’错误求助

解决VS Code扩展直接运行node extension.js报"Cannot find module 'vscode'"的问题

错误原因

  • vscode模块并非公开npm包,它是由VS Code宿主环境在扩展运行时注入的专属API,直接用Node.js执行扩展文件自然找不到该模块。
  • 你安装的@types/vscode只是TypeScript类型定义文件,仅用于代码提示和类型校验,不包含实际的API实现逻辑。
  • 你的extension.js中手动调用了activate()函数,而该函数是VS Code在触发扩展激活条件时自动调用的,手动执行会在无VS Code环境的情况下触发错误。

正确运行扩展的方法

方法1:使用VS Code调试功能

  1. 打开扩展项目所在文件夹
  2. 点击左侧「运行和调试」面板(快捷键Ctrl+Shift+D)
  3. 选择「Launch Extension」配置,点击启动按钮,VS Code会打开新的扩展开发窗口,你的扩展将在该窗口中激活运行。

方法2:使用命令行启动扩展

  1. 修改package.json,添加启动脚本:
{
    // ...其他原有配置
    "scripts": {
        "start": "code --extensionDevelopmentPath=."
    }
}
  1. 执行npm run start或yarn start,VS Code会启动加载了当前扩展的新窗口。

修复扩展代码

删除extension.js末尾的activate()调用,让VS Code自动管理扩展的激活逻辑:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate() {
    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "helloworld-minimal-sample" is now active!');
}

// this method is called when your extension is deactivated
function deactivate() {}

// 移除下面这行手动调用的代码
// activate()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:33:25