Reputation: 2355
I am new to Javascript and I am trying to learn modules from a tutorial. In have a folder in visual studio code/VScode which has two files, script.js & external.js.
Script.js imports content from external.js and prints text to console. I get the below error when I run script.js from vs code, with node.js run configuration. Can someone please tell me why this happens and how to fix it ? In comparison, imports in Java are simple.
import {keyValue} from './external.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1070:16)
at Module._compile (internal/modules/cjs/loader.js:1120:27)
external.js :
export let keyValue = 1000;
script.js :
import {keyValue} from './external.js';
console.log(keyValue);
UPDATES : Node version - v12.16.2, upgraded to v14.4.0.
Upvotes: 5
Views: 7248
Reputation: 6197
{ type: "module" }
to package.json.{
...
scripts: "...",
type: "module"
}
.js
to .mjs
.js
to .mjs
, and run with additional params --experimental-modules
.node --experimental-modules script.js
You can also fix the import statement outside a module
issue
by not using the import statement and using the dynamic import function instead.
script.js
import("./external.js").then((module) => {
console.log(module.keyValue);
});
This form also supports the await
keyword.
let module = await import('./external.js');
console.log(module.keyValue)
Upvotes: 5
Reputation: 113
it's because you are using es6 modules instead of the default module system for node which is common js. you could either use babel to transpile it or to use the .mjs extension
Upvotes: -1