npm 抱怨模块外的导入。那是什么意思?

时间:2021-07-07 19:37:56

标签: node.js module mocha.js

作为一个个人项目,我正在尝试通过实现纸牌游戏“Great Dalmuti”的在线版本来学习一些基本的 JavaScript 编程。

现在,我正在尝试使用 TDD 实现游戏中的一些基本元素。您可以在以下位置查看我的代码的当前状态:https://github.com/spierepf/great-dalmuti

我遇到的问题是声明:

import { INVALID_MOVE } from 'boardgame.io/core';

我从 boardgame.io 教程中复制粘贴的:https://boardgame.io/documentation/#/tutorial?id=validating-moves

我得到的错误是:

$ npm test

> great-dalmuti@1.0.0 test
> mocha

(node:21353) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)

/home/peter/Nextcloud/boardgame.io/great-dalmuti/test/Game.test.js:3
import { INVALID_MOVE } from 'boardgame.io/core';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at ModuleWrap.<anonymous> (internal/modules/esm/translators.js:199:29)
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async formattedImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:7:14)
    at async Object.exports.requireOrImport (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:48:32)
    at async Object.exports.loadFilesAsync (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/esm-utils.js:74:20)
    at async singleRun (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run-helpers.js:125:3)
    at async Object.exports.handler (/home/peter/Nextcloud/boardgame.io/great-dalmuti/node_modules/mocha/lib/cli/run.js:366:5)

我在网上找到的内容涉及重命名具有不同扩展名的文件(主要是 .cjs.mjs)或添加 <script/> 标签,或通过编辑 {{1} }.到目前为止,这些选项都没有奏效。

我已经按照完整的 boardgame.io 教程进行了井字游戏,并且已经成功运行。它似乎不涉及模块、外来扩展或特殊标签。本教程不涉及 TDD 或自动化测试。

1 个答案:

答案 0 :(得分:1)

Node 无法在本地执行 importexport 语句。正如您在帖子中所说,有 2-3 种方法可以做到这一点,例如 1) 将扩展名更改为 mjs,2) 更改 package.json 以使项目成为模块。我认为您无法正确使用它,因为您正在运行测试用例。

因此,对您来说最好的办法是为您的存储库添加 babel 支持。

npm install --save-dev @babel/cli @babel/core @babel/node @babel/register @babel/preset-env

制作一个名为 .babelrc 的文件:

{
  "presets": ["@babel/preset-env"]
}

运行:

mocha --compilers js:@babel/register 

您也可以将 test 脚本更改为此。

您可以关注更详细的博客,例如this