How To Fix The Error “To Load An ES Module, Set ‘Type’ – ‘Module'” In JavaScript

To load an ES module, set “type” – “module” in JavaScript

If you are having trouble with the error: To load an ES module, set “type” – “module” in JavaScript, let’s follow this article. I will give you some solutions to fix it. Let’s go into detail now.

The reason for the error “To load an ES module, set ‘type’ – ‘module’ in JavaScript

The error happens when you try using ES6 syntax like import-export without setting in file ‘package.json’. So you get a conflict.

Example of error:

const sum = (str) => {
  console.log(str);
};
import logText from "./logText";
logText("Hello");
Error: (node:17308) Warning: To load an ES module, set "type": "module" in the package.json or
use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\Workspace\CTV WORK\javascript\index.js:1
import logText from "./logText";
^^^^^^
 
SyntaxError: Cannot use import statement outside a module
	at ...

How to fix this error?

Solution: Setting ‘package.json.’

You will have to initiate the project if you want to use nodejs or ES6 modules syntax.

Step 1: Initiate project

You can init your project by this command:

npm init

Result:

{
  "name": "javascript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Step 2: Set ‘type’

You will have to set the ‘type’ property in the ‘package.json’ file to load ES modules.

Example:

{
  "name": "javascript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
 
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC" 
}

And your code will run.

Now you can import functions, variables, etc., from another file.

Example:

import logText from "./dialog.js";
dialog.logText("Hello"); 
 
const logText= (str) => {
  console.log(str);
};

function response(){
    console.log("Hi")
}

export default logText

Output:

Hello

You can also import more than one, like the code below.

Example:

const logText= (str) => {
  console.log(str);
};

function response(){
    console.log("Hi")
}

export {logText,response}
import * as dialog from "./dialog.js";
dialog.logText("Hello");
dialog.response();

Here I import logText and response function separately. Then I use the ‘*’ symbol to import all functions that I export to the dialog.js file. You can also export separate like this:

import {logText,response} from "./dialog.js";
dialog.logText("Hello");
dialog.response();

Output:

Hello
Hi

Summary

In this tutorial, I showed and explained how to fix the error: To load an ES module, set “type” – “module” in JavaScript. You should set ‘type’ property in package.json to ‘module.’

Maybe you are interested:

Leave a Reply

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