Typescript: Cannot use import statement outside a module

Solution 1:

Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.

This however causes a problem with the current code because although you are using an ES6 import {} statement you are exporting using the commonJS module.exports = {} syntax, and Node’s ES module loader will have an issue with it. There are two ways to deal with it:

  1. Keep the module.exports but tell Node to interpret this file as commonJS by giving it a .cjs extension.
  2. Change the export statement to ES2015 syntax: export function execute(…)..

The first option could get a bit tricky because the compiler will output .js files and you’d have to change it to .cjs all the time (as far as I know). With the second option you should be able to run the file with Node (including the --experimental-modules flag for versions < 13.8).

If you absolutely need to use commonJS, perhaps it is better to install the type definitions for Node: @types/node and change the import to commonJS format: require('abc') and keep the rest of the settings as they are (though you can add “type”: “commonjs” to package.json to be explicit).

Solution 2:

Make sure your "main" field in package.json is pointing to the compiled index.js and not the index.ts

Solution 3:

I had very similar issue. I had to install nodemon and always start script through nodemon index.ts

yarn add -D nodemon

package.json

"scripts": {
   "start": "nodemon index.ts"
}

or to specify the file from the command line

package.json

"scripts": {
   "nodemon": "nodemon $1"
}

Solution 4:

There can be a lot of of possibilities for getting,

SyntaxError: Cannot use import statement outside a module

while running typescript.

In my setup, I was importing a module called, AbModule (AbModule has class AbClassName) from my script testab.ts.

testab.ts had import stmt,

import {AbClassName} = 'testAdapterDir/AbModule.po.ts';

However, AbModule had all *.ts files and there were *.js files were not present. fix is,

You may get errors in running the below code but you can safely ignore them.

cd AbModule path
tsc *.ts

Now AbModule should contain compiled files all *.js too. Now run testab.ts and noticed that the mentioned error does not exist anymore,