Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

node.js - Node v13 / Jest / ES6 — native support for modules without babel or esm

Is it possible to test ES6 Modules with Jest without esm or babel? Since node v13 supports es6 natively have tried:

//package.json
{
  …
  "type": "module"
  …
}



//__tests__/a.js
import Foo from '../src/Foo.js';


$ npx jest

Jest encountered an unexpected token
…
Details:

/home/node/xxx/__tests__/a.js:1
import Foo from '../src/Foo.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module

When babel is added a transpiler, it works, but can es6 modules be used natively as well?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, it is possible from [email protected]. From this version, there is a native support of esm, so you will not have to transpile your code with babel anymore.

It is not documented yet, but according to this issue you have to do 3 easy steps to achieve that (At the time of writing this answer):

  • Make sure you don't transform away import statements by setting transform: {} in your jest config file
  • Run node@^12.16.0 || >=13.2.0 with --experimental-vm-modules flag
  • Run your test with jest-environment-node or jest-environment-jsdom-sixteen.

So your jest config file should contain at least this:

export default {
    testEnvironment: 'jest-environment-node',
    transform: {}
    ...
};

And to set --experimental-vm-modules flag, you will have to run Jest from package.json as follows (I hope this will change in the future):

"scripts": {
    "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}

I hope, this answer was helpful to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...