Home > Software design >  Unexpected identifier when exporting typescript class
Unexpected identifier when exporting typescript class

Time:11-23

I have a typescript class called Polynomial, and I want to create a npm module with it. For that, I'm trying to test it with mocha, with this script:

//Polynomial.test.js
const Polynomial = require('./Polynomial.ts'); 
const assert = require('assert').strict;

describe("First test", function() {
    it("test", function() {
        let p = new Polynomial();
        assert(p.equals(new Polynomial("0")));
    });
});

When I do npm test I get the error Unexpected identifier at the very first line of the class, which look like:

// Polynomial.ts
class Polynomial {
  private coefMap: Map<string, string> = new Map();  // <--- Error
  // ...
}
module.exports = Polynomial;

This is the package.json:

{
  "name": "multivariate-polynomial",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "mocha Polynomial.test.js"
  }
}

And the tsconfig.json:

{
    "compilerOptions": {
      "target": "es5",
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "module": "commonjs",
      "declaration": true,
      "outDir": "./lib",
      "strict": true
    },
  }

Any hint in what the problem is?

CodePudding user response:

Map is not available for ES5 lib. You can either:

  • add lib equal to ES2015 (alias for ES6)
  • change target to es2015 (alias for es6).

Intro to the TSConfig Reference - target

Changing target also changes the default value of lib. You may “mix and match” target and lib settings as desired, but you could just set target for convenience.

See answer to: ES6 Map in Typescript

CodePudding user response:

Changing lib and target didn't fix the issue, but I created a new project following the steps described here:

Setup a new TypeScript project with Mocha support

and now it works.

Thanks.

  • Related