Skip to content


SyntaxError: Cannot use import statement outside a module (NodeJS / TypeScript)

I’ve been using TypeScript for about 5 years, and until now, I had been stuck to compiling to the ES5 target, because any time I would try something more recent, I would get an error saying: “SyntaxError: Cannot use import statement outside a module”.
This didn’t seem like a big deal, because TS is convenient in that it keeps your always newer code compatible with old JS standards, but still I finally decided to dig a little.

The first interesting thing I found was this. Basically, it says “In your package.json file, simply add “type”:“module””. That lead nowhere, however, while typing it, I noticed the only other alternative to “module” was “commonjs”.

Digging a bit more, I found that tsconfig has a similar parameter, called “module”. So I tired setting it to commonjs and… it worked. Looking back at it, this value was in the community base tsconfig for Node 14, meh. Should have just tried that in the first place. Anyway, here’s my current tsconfig:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "allowSyntheticDefaultImports": true,
    "noImplicitAny" : true,
    "strictPropertyInitialization": true,
    "strictNullChecks": true,
    "esModuleInterop": true,
    "lib": [
      "es2020"
    ],
    "skipLibCheck": false,
    "alwaysStrict": true,
    "removeComments": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "*": [
        "*",
        "C:/Users/myaccount/AppData/Roaming/npm/node_modules/*",
        "/usr/local/lib/node_modules/*"
      ]
    }
  },
  "exclude": [
    "node_modules"
  ]
}

Posted in JavaScript / TypeScript / Node.js, web development.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA