Sunday, August 7, 2022
HomeWordPress DevelopmentThe best way to repair 'Uncaught SyntaxError: Can not use import assertion...

The best way to repair ‘Uncaught SyntaxError: Can not use import assertion outdoors a module’


On this fast information we’ll take a look at how one can remedy the quite common error, “Uncaught SyntaxError: Can not use import assertion outdoors a module”. This error arises once we attempt to use import inside a undertaking which isn’t arrange for modules – so let’s take a look at how one can resolve it.



Resolving the import assertion outdoors a module error

The explanation why this error happens is as a result of we have now to explicitly inform Javascript that the file in query is a module, to be able to use the import assertion. For instance, in case you are utilizing the road beneath, and you haven’t informed Javascript that the file is a module, it is going to throw an error:

import fs from 'fs'
Enter fullscreen mode

Exit fullscreen mode

Relying on the place you’re getting the error, there are a number of other ways to resolve it.



Resolving the import module error in Node.js

In case you are utilizing Node.js, this error may be resolved in two methods. The primary is to replace your bundle.json to inform Node.js that this whole undertaking is a module. Open up your bundle.json, and on the prime stage, add "sort": "module". For instance, my bundle.json will seem like this:

{
    // ... different bundle.json stuff
    "sort": "module"
    // ... different bundle.json stuff
}
Enter fullscreen mode

Exit fullscreen mode

This can resolve the problem instantly. Nonetheless, in some edge instances, chances are you’ll discover you may have points with this, and different elements of your code might begin throwing errors. Should you solely need one file in your undertaking to assist import, then change the file extension to .mjs. For instance, in case your import was in index.js, rename index.js to index.mjs. Now your situation can be resolved.



Resolving the import module error in script tags

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

<script src="mymodule.js"></script>
Enter fullscreen mode

Exit fullscreen mode

On this case, if mymodule.js comprises an import assertion, it will not work. To resolve this, add sort="module" to your script tag:

<script sort="module" src="mymodule.js"></script>
Enter fullscreen mode

Exit fullscreen mode

Now you will by no means have points with import once more.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments