I can't use imports because I always have this error:
(function (exports, require, module, __filename, __dirname) { import { expect } from 'chai';
SyntaxError: Unexpected token import
In my file index.test.ts
I have this:
import { expect } from 'chai';
describe('Hello function', () => {
it('should return hello world', () => {
const result = hello();
expect(result).to.equal('Hello World!');
});
});
In my package.json
I have this:
"scripts": {
"test": "mocha --reporter spec --compilers test/**/*.test.js",
},
My tsconfig.json
:
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": [
"dom",
"es2015"
],
"outDir": "dist",
"strict": false
}
}
Please tell me that how can I use imports?
mocha + typescript + es6 module
{
"compilerOptions": {
...
"module": "commonjs"
}
}
--require ts-node/register
--require @babel/register
...
This works for me.
npx mocha --require ts-node/register --require esm src/**/*.spec.ts
Or in package.json
scripts (both options work, choose whichever you like):
"scripts": {
"test": "mocha -r esm -r ts-node/register src/**/*.spec.ts",
"test-ts": "ts-mocha -r esm -p tsconfig.json src/**/*.spec.ts"
}
And don't forget to add esm
to devDependencies
:
npm install --save-dev esm
so in package.json it is gonna be
"devDependencies": {
"esm": "^3.2.25"
}
P.S. Thanks @user318830, you made me realize it is possible to have several '--require' specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With