首页 > 解决方案 > 带有 npm 模块的“语法错误:无法在模块外使用 import 语句”

问题描述

我正在尝试使用 npm 模块(https://github.com/AmyrAhmady/steamdb-js),但是当我使用示例代码时,出现“SyntaxError:无法在模块外使用导入语句”。

这是示例代码:

import { Game } from "steamdb-js";

async function main() {
  const game = new Game(271590);
  await game.fetchData();
  const data = await game.parse();
  //console.log(data); // This prints out all parsed data, you can use it for easier in-code usage
  console.log(game.getGameInfo());
}

main();

这是错误:

PS C:\Users\user\Desktop\Développement\TEST> node .\index.js
C:\Users\selim\Desktop\Développement\TEST\index.js:1
import { Game } from "steamdb-js";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1116:16)
    at Module._compile (internal/modules/cjs/loader.js:1164:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

是我的错还是 npm 模块的错?

标签: node.jsnpmimport

解决方案


自从创建此线程以来已经有一段时间了,但是我认为当涉及到我制作的库时,我有责任回答这个问题。

首先,example 和 steamdb-js 代码使用 ES5 标准(例如importexport语法)你需要先启用这些,你可以使用最新的可用 Nodejs 版本,或者使用转译器;如果您不使用 Node +v13 或不知道如何操作,这是我的建议:

现在一切都应该正常工作并且steamdb-js应该能够“”“执行”“”

我在强调execute因为现在有一个问题,我们知道 steamdb 正在使用 CloudFlare,他们启用了“Under Attack”模式,这是一个可以绕过的问题,但可悲的部分是由于 CloudFlare 的新变化,我怀疑当前那里的图书馆目前正在工作,我会在找到方法后立即更新我的图书馆。

谢谢!

(我第一次在 Stackoverflow 上发帖!)


推荐阅读