2 Quick and Easy Ways to Fix 'Uncaught SyntaxError: Cannot use import statement outside a module'

Written by smpnjn | Published 2022/08/08
Tech Story Tags: nodejs | javascript-development | web-development | javascript | javascript-frameworks | javascript-tutorial | debugging | software-development

TLDRNode.js error: Cannot use import statement outside a module. This error arises when we try to use `import` inside of a project which is not set up for modules. The reason why this error occurs is because we have to explicitly tell Javascript that the file in question is a `module` The error can be resolved in two ways: updating your package.json and changing the file extension to 'mjs' The second place this error can occur is in a script tag, like this: Add 'type="my module" to your script tag.via the TL;DR App

In this quick guide we'll look at how you can solve the very common error, "Uncaught SyntaxError: Cannot use import statement outside a module". This error arises when we try to use import inside of a project which is not set up for modules - so let's look at how you can resolve it.

Resolving the import statement outside a module error

The reason why this error occurs is because we have to explicitly tell Javascript that the file in question is a module, in order to use the import statement. For example, if you are using the line below, and you have not told Javascript that the file is a module, it will throw an error:

import fs from 'fs'

Depending on where you are getting the error, there are a few different ways to resolve it.

Resolving the import module error in Node.js

If you are using Node.js, this error can be resolved in two ways. The first is to update your package.json to tell Node.js that this entire project is a module. Open up your package.json, and at the top level, add "type": "module". For example, my package.json will look like this:

{
    // ... other package.json stuff
    "type": "module"
    // ... other package.json stuff
}

This will resolve the issue immediately. However, in some edge cases, you may find you have issues with this, and other parts of your code may start throwing errors. If you only want one file in your project to support import, then change the file extension to .mjs. For example, if your import was in index.js, rename index.js to index.mjs. Now your issue will be resolved.

Resolving the import module error in script tags

The second place this error can occur is in a script tag, like this:

<script src="mymodule.js"></script>

In this case, if mymodule.js contains an import statement, it won't work. To resolve this, add type="module" to your script tag:

<script type="module" src="mymodule.js"></script>

Now you'll never have issues with import again.


Also published here.


Written by smpnjn | Product, Engineering, Web
Published by HackerNoon on 2022/08/08