Is it possible to use ES6 modules in Mocha tests?

后端 未结 2 1149
太阳男子
太阳男子 2021-02-07 13:51

ES6, Windows 10 x64, Node.js 8.6.0, Mocha 3.5.3

Is it possible to use ES6 modules in Mocha tests? I have the problems with export and import ke

2条回答
  •  庸人自扰
    2021-02-07 14:17

    Mocha has support for ESM from version 7.1.0 onward (release: Feb. 26, 2020).

    This requires Node 12.11.0 or higher, and is subject to the current restrictions/limitations of using modules in Node:

    • Either you must use .mjs file extensions for source files that use ES modules, or you must have "type": "module" in your package.json
    • You can't use named imports when importing from CommonJS modules

    And so on.

    Another option is to use the esm package, which is not subject to the above limitations:

    mocha -r esm
    

    My personal experience as of yet is that trying to take advantage of Mocha's new, inherent ESM support is still a considerable burden, but using the esm package is quite seamless.

提交回复
热议问题