0

So i have this very very simple dummy test:

import {expect}  from 'chai';

describe('calculate', function () {
    it('add', function () {
        let result = 2 + 5;
        expect(result).equal(7);
    });
});

Here i get the following error when i run it:

(function (exports, require, module, __filename, __dirname) { import { expect } from 'chai';
                                                                     ^

SyntaxError: Unexpected token {

Can anyone tell me whats going on?

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

1 Answers1

2

You need to transpile your code to use commonjs imports. You can use babel for such a task, see the docs https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs.

Via cli you can run babel --plugins @babel/plugin-transform-modules-commonjs script.js and then simply run your script.

If you don't want to use either transpilation (using babel or whatever) or commonjs you could use a loader such as esm: https://www.npmjs.com/package/esm.

From the docs, after running yarn add esm you can just node -r esm main.js.

adz5A
  • 2,012
  • 9
  • 10
  • I dont have babel installed yet this is not suppose to run in the browser it is just suppose to be an Nodejs module – Marc Rasmussen Sep 04 '20 at 08:39
  • babel is not only used for targeting the browser these days. As a matter of fact it can be considered good practice to typecheck your code using typescript and transpile it using babel (we do this on a server side project). Your problem can be solved by using commonjs imports `const { expect } = require("chai")` or something like that, since es6 are still experimental in node – adz5A Sep 04 '20 at 14:27