【问题标题】:Syntax error: Cannot use import statement outside a module语法错误:不能在模块外使用 import 语句
【发布时间】:2020-04-19 00:45:33
【问题描述】:

当我尝试在 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
}

【问题讨论】:

  • 请向我们展示导致此错误的代码。否则我们将无法为您提供帮助。
  • 当然,我基本上是使用“yo code”和 NPM 来创建一个 Extension。
  • 您能否为lanch.json添加更多信息

标签: javascript visual-studio-code vscode-debugger


【解决方案1】:

VS 代码扩展运行在原生不支持模块的 Node 环境中(所以不支持 import 和 export)。

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

const vscode = require('vscode');

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

【讨论】:

  • 谢谢。我会用什么来代替导入和导出?
  • require and exports: nodejs.org/api/modules.html#modules_modules 或者使用我提到的编译器
  • 嗨,马特,您能详细说明一下“将代码编译到目标节点”吗?
  • @laike9m Typescript 需要先编译为 Javascript(然后由 Node.JS 运行)才能运行。 typescriptlang.org/docs/handbook/typescript-from-scratch.html
  • 我正在使用 TypeScript,我正在尝试加载一个使用 import 的 JS 依赖项,所以我将 "module": "ES2020", 放在我的 tsconfig.json 中,我得到了问题中的错误。
猜你喜欢
  • 2020-05-09
  • 2020-09-12
  • 2022-10-23
  • 1970-01-01
  • 2022-02-12
  • 2020-02-09
  • 2020-10-10
相关资源
最近更新 更多