语法错误:无法在模块外部使用 import 语句

Sha*_*bir 8 javascript visual-studio-code vscode-debugger

当我尝试在 VSC 中运行调试器时,我不断收到此错误消息。有人可以帮忙吗?这是一个屏幕截图:

我对编程和课程还很陌生,请尽可能让解释保持非常基本的内容。

在此输入图像描述

这是 JS 文件的代码。我使用 Yo Code 和 NPM 生成了一个基本的 Visual Studio 代码扩展。

    // The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import { commands, window } from '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(context) {

// 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 "content-helper" is now 
    active!');

    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    let disposable = commands.registerCommand('extension.helloWorld', function () {
        // The code you place here will be executed every time your command is executed

        // Display a message box to the user
        window.showInformationMessage('Hello World!');
    });

    context.subscriptions.push(disposable);
}
const _activate = activate;
export { _activate as activate };

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

export default {
    activate,
    deactivate
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ner 4

VS 代码扩展在 Node 环境中运行,该环境本身不支持模块(因此没有importexport)。

yo codeimport仅在创建 TypeScript 扩展时使用。对于 js 扩展,yo code请改为使用require

const vscode = require('vscode');
Run Code Online (Sandbox Code Playgroud)

要在 VS Code 扩展中使用import,您必须使用 TypeScript 或 webpack 等工具将代码编译到目标 Node

  • 你好,Matt,你能详细说明一下“将代码编译到目标节点”吗? (3认同)
  • 我正在使用 TypeScript,并且尝试加载使用 `import` 的 JS 依赖项,因此我将 `"module": "ES2020",` 放入我的 tsconfig.json 中,并在问题中收到错误。 (2认同)