How to fix ‘Uncaught SyntaxError: Cannot use import statement outside a module’

how-to-fix-‘uncaught-syntaxerror:-cannot-use-import-statement-outside-a-module’

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:


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


Now you’ll never have issues with import again.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
bluehost-review-the-good-and-bad-for-2022

Bluehost review-the good and bad for 2022

Next Post
gsoc-2022-circuitverse-|-week-7-and-8-report

GSoC 2022 CircuitVerse | Week 7 and 8 Report

Related Posts

Vue3 重点难点全解析:这些坑你踩过几个?

Vue3 发布已久,Composition API、响应式重构、TypeScript 支持等特性让人眼前一亮,但真正深入项目后,才发现“会用”和“用对”之间隔着不少难点。本文梳理了 Vue3 开发中高频踩坑的重点难点,希望能帮你少走弯路。 一、响应式系统的“糖”与“坑” Vue3 用 Proxy 代替了 Object.defineProperty,解决了 Vue2 中对象新增属性不响应、数组索引和长度监听等历史难题。但新的响应式 API 也带来了新的心智负担。 1. ref…
Read More