Skip to content

Fix: Syntax error: Cannot use import statement outside a module

  • by
  • 2 min read

As easy as programming has become over the years, there are still plenty of hoops for developers to jump through when they’re coding something, be it any language.

In this article, we’re taking a look at the “cannot use import statement outside a module” error in Node.js and telling you how to fix the problem.

Also read: Error: Cannot find module express: 3 Fixes


Change the script type

One of the first things you should do when getting this error is change your script type to a module. Here’s an example.

What you’re doing here is essentially changing the script type from plain JavaScript to module allowing them to be used in the application. 


Update the package.json file

Another possible cause of the error is because you’re project isn’t initialised to use modules properly. You can do this by updating your package.json file by adding the following snippet. 

{
  "type": "module",
}

If you don’t see a package.json file, open a terminal in the root directory of your project and type the following command to initialise your project.

npm init -y

Also read: How to fix ‘Objects are not valid as a react child’ error?


Replace import with require

Note that when using modules, you’ll need to choose between import or require as you can’t natively mix and match between the two. So instead of using import like this

import package from 'something-package'

Use require like this

cost package = require('something-package')

Or vice versa depending on your project. 


Changing module type

If you’re experiencing this problem in a TypeScript project, try changing the module type to commonjs in your tsconfig.json file. 

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "esModuleInterop": true,
    // other options
  }
}

These errors come up in TypeScript projects when users try to run TypeScript files using something like node. Try tor transpile your .ts files with a package like ts-node before running them to ensure you don’t get the error again. 

Also read: What is ‘_xsrf argument missing from post’? 3 Fixes

nv-author-image

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>