Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Unexpected token import mocha

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?

like image 748
Brygom Avatar asked Feb 07 '19 06:02

Brygom


2 Answers

mocha + typescript + es6 module

  1. tsconfig.json
{
  "compilerOptions": {
    ...
    "module": "commonjs"
  }
}
  1. mocha.opts
--require ts-node/register
--require @babel/register
...
like image 121
user3148830 Avatar answered Oct 23 '22 01:10

user3148830


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.

like image 42
folex Avatar answered Oct 23 '22 01:10

folex