node.jstypescripttsconfighashids

Exception when importing hashids in typescript


I'm trying to import hashids in Typescript:

You can clone the code from here

========== index.ts ==========

import Hashids from "hashids";
const encoder = new Hashids();

But I get the next error:

=========== Console =========

export { Hashids as default };
^^^^^^
SyntaxError: Unexpected token 'export'
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/var/www/persona-service/src/Example.ts:1:1)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Module.m._compile (/var/www/persona-service/node_modules/ts-node/src/index.ts:814:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:995:10)

This is my tsconfig.json

{
  "compilerOptions": {
    "incremental": true,
    "moduleResolution": "node",
    "module": "CommonJS",
    "esModuleInterop": true,
    "target": "es6",
    "types": [
      "node",
      "express",
      "hashids"
    ]
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

I'm also using nodemon with this config:

{
  "watch" : ["src"],
  "ext": "ts",
  "exec": "ts-node ./src/index.ts"
}

What can be happening here?


Solution

  • Checking the git repo for the hashids package found an issue relating to import for certain node versions:

    hashids issue on the repo

    A workaround mentioned there is to use require instead of import

    const Hashids = require('hashids/cjs');
    

    I hope this gets you back on track.