6

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.

2
  • your external.js file needs to be inside the root/modules folder Commented Jun 18, 2020 at 6:29
  • 1
    you need to tell node that you are using esm and not cjs. Either package.json: type: module or name your files with ext .mjs or use esm node -r esm script.js Commented Jun 18, 2020 at 6:32

2 Answers 2

5

What's the version of node.js?

If node.js is version 13 or above, you can do either:

  • add { type: "module" } to package.json.
{
  ...
  scripts: "...",
  type: "module"
}
  • rename .js to .mjs

If it's under 13, rename .js to .mjs, and run with additional params --experimental-modules.

node --experimental-modules script.js

Or

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I upgraded it to v14.4.0. My tutorial does not mention package.json, but i setup one with npm init now. I am trying to understand how to make external.js a module which script.js can use.
@MasterJoe2 To make external.js as a module, you need to export it. and in ur script.js, import it. you can start from here, tutorialsteacher.com/nodejs/nodejs-module-exports
or u can update your post, including all files and file structures.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.