"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6

SyntaxError: Cannot use import statement outside a module

Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:

Option 1

In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.

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

Option 2

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

Cannot use import statement outside a module CLIENT-SIDE

It loads the whole module, not just the part that I want

It always does, you cannot avoid that. This also happens when you use import {…} from '…' - it just doesn't import everything into the current module scope. Just like when you call import(…), you don't have to use all available parts:

buttonX.addEventListener('click', async () => {
const { sayHi: a } = await import("./sayHi.js");
a();
});

Typescript SyntaxError: Cannot use import statement outside a module (side file containing functions)

Fixed by changing:

import {util} from "./utils/util"

To:

const util = require('./utils/util')
// or
const { sleep, random, eatAny, clickItem, lookAtEntity} = require('./utils/util')

Afterall I don't know why compiling with tsc had been working well while webstorm was throwing out error. I just changed the import ES6 syntax to require() CommonJS.



Related Topics



Leave a reply



Submit