语法错误:无法在模块外使用导入语句。

8

当我尝试在VSC中运行调试器时,一直收到这个错误提示,请问有人可以帮忙吗?以下是截图:

我基本上是一个编程新手,正在跟着一门课程学习,请尽可能简单易懂地解释。

enter image description here

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

    // 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
}

请展示导致此错误的代码。否则我们将无法帮助您。 - emeraldsanto
当然,我基本上使用了“yo code”和NPM来创建一个扩展。 - Shabbir
你能为 lanch.json 添加更多信息吗? - huoxudong125
1个回答

4

VS Code扩展运行在Node环境中,该环境不支持原生模块(因此没有importexport)。

yo code仅在创建TypeScript扩展时使用import。 对于js扩展,yo code使用require代替:

const vscode = require('vscode');

在VS Code扩展中使用import,必须将代码编译为Node目标,可以使用TypeScript或类似webpack的工具进行编译。


谢谢。我可以使用什么代替import和export? - Shabbir
requireexports:https://nodejs.org/api/modules.html#modules_modules 或者使用我提到的编译器。 - Matt Bierner
3
嗨,马特,你能详细说明一下“将代码编译成目标Node”的意思吗? - laike9m
@laike9m TypeScript 需要先编译成 Javascript(然后由 Node.JS 运行)才能执行。 https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html - Jan
2
我正在使用TypeScript,并尝试加载一个使用import的JS依赖项,因此我在我的tsconfig.json中放置了"module": "ES2020",但我遇到了问题。 - user3064538

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接