Сегодня я начал писать новый проект на Node.js и при первом же запуске получил ошибку:
const express = require('express');
^
ReferenceError: require is not defined
at ModuleJob.run (node:internal/modules/esm/module_job:152:23)
at async Loader.import (node:internal/modules/esm/loader:166:24)
at async Object.loadESM (node:internal/process/esm_loader:68:5)
Первым делом я проверил установленную версию Node.js:
Тут проблем не было
v15.5.1
Выглядело это довольно странно и раньше в серверных приложениях я такой ошибкой не сталкивался.
Быстрый поиск на stackoverflow нашел несколько тем, в которых говорят, что require не работает в браузере и советуют использовать webpack или browserify.
Еще несколько минут и я нашел то, что мне было нужно. Похоже, что в версиях Node.js 14+ ошибка ReferenceError: require is not defined может встречаться и на сервере.
Проблема в том, что в файле package.json была такая строка:
С ее помощью активируется подключение npm модулей через ключевое слово import.
Решение
Чтобы избавиться от ошибки require is not defined в Node.js можно сделать 3 вещи:
-
изменить тип модулей в
package.jsonнаcommonjs: -
удалить строку
"type": "module"из файлаpackage.json -
изменить тип подключения модулей на
import:// const express = require('express'); import express from 'express';

The ReferenceError: require is not defined error means the require function is undefined under the current JavaScript environment.
This error usually happens when you try to import a module in your JavaScript file.
Here’s an example code that triggers this error:
const axios = require("axios");
// ReferenceError: require is not defined
Your JavaScript environment doesn’t understand how to handle the call to require function as shown above.
To fix this error, you need to make the require function available under your JavaScript environment.
Depending on where you run the script, there are several solutions you can take:
Let’s see how to fix the error from the browser first.
Fix require is not defined in the browser
The JavaScript require() function is only available by default in Node.js environment.
This means the browser doesn’t know what you mean with the require() call in your code.
But require() is actually not needed because browsers automatically load all the <script> files you added to your HTML file.
For example, suppose you have a lib.js file with the following code:
function hello() {
alert("Hello World!");
}
Then you add it to your HTML file as follows:
<body>
<!-- 👇 add a script -->
<script src="lib.js"></script>
</body>
The function hello() is already loaded just like that. You can call the hello() function anytime after the <script> tag above.
Here’s an example:
<body>
<script src="lib.js"></script>
<!-- 👇 call the lib.js function -->
<script>
hello();
</script>
</body>
A browser load all your <script> tags from top to bottom.
After a <script> tag has been loaded, you can call its code from anywhere outside of it.
Server-side environments like Node doesn’t have the <script> tag, so it needs the require() function.
Use ESM import/ export syntax
If you need a require-like syntax, then you can use the ESM import/export syntax from a browser environment.
Modern browsers like Chrome, Safari, and Firefox support import/export syntax when you load a script with module type.
First, you need to create exports in your script. Suppose you have a helper.js file with an exported function as follows:
function greetings() {
alert("Using ESM import/export syntax");
}
export { greetings };
The exported function can then be imported into another script.
Create an HTML file and load the script. Add the type attribute as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- 👇 don't forget the type="module" attribute -->
<script type="module" src="helper.js"></script>
<script type="module" src="process.js"></script>
</body>
</html>
In the process.js file, you can import the helper.js file as shown below:
import { greetings } from "./helper.js";
greetings();
You should see an alert box called from the process.js file.
You can also use the import statement right in the HTML file like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<script type="module" src="helper.js"></script>
<!-- 👇 import here -->
<script type="module">
import { greetings } from "./helper.js";
greetings();
</script>
</body>
</html>
Using RequireJS on your code.
If you want to use the require() function in a browser, then you need to add RequireJS to your script.
RequireJS is a module loader library for in-browser use. To add it to your project, you need to download the latest RequireJS release and put it in your scripts/ folder.
Next, you need to call the script on your main HTML header as follows:
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Tutorial</title>
<script data-main="scripts/app" src="scripts/require.js"></script>
</head>
<body>
<h1 id="header">My Sample Project</h1>
</body>
</html>
The data-main attribute is a special attribute that’s used by RequireJS to load a specific script right after RequireJS is loaded. In the case of above, scripts/app.js file will be loaded.
You can load any script you need to use inside the app.js file.
Suppose you need to include the Lodash library in your file. You first need to download the script from the website, then include the lodash.js script in the scripts/ folder.
Your project structure should look as follows:
├── index.html
└── scripts
├── app.js
├── lodash.js
└── require.js
Now all you need to do is use requirejs function to load lodash, then pass it to the callback function.
Take a look at the following example:
requirejs(["lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
The code above shows how to use RequireJS to load the lodash library.
Once it’s loaded, the <h1> element will be selected, and the textContent will be assigned as “hello world” text that is transformed to uppercase by lodash.uppercase() call.
You can wait until the whole DOM is loaded before loading scripts by listening to DOMContentLoaded event as follows:
document.addEventListener("DOMContentLoaded", function () {
requirejs(["lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
});
Finally, you may also remove the data-main attribute and add the <script> tag right at the end of the <body> tag as follows:
<!DOCTYPE html>
<html>
<head>
<title>RequireJS Tutorial</title>
<script src="scripts/require.js"></script>
</head>
<body>
<h1 id="header">My Sample Project</h1>
<script>
document.addEventListener("DOMContentLoaded", function () {
requirejs(["scripts/lodash"], function (lodash) {
const headerEl = document.getElementById("header");
headerEl.textContent = lodash.upperCase("hello world");
});
});
</script>
</body>
</html>
Feel free to restructure your script to meet your project requirements.
You can download an example code on this requirejs-starter repository at GitHub.
Now you’ve learned how to use RequireJS in a browser. Personally, I think it’s far easier to use ESM import/export syntax because popular browsers already support it by default.
Next, let’s see how to fix the error on the server-side
Node application type is set to module in package.json file
The require() function is available in Node.js by default, so you only need to specify the library you want to load as its argument.
For example, here’s how to load the lodash library from Node:
// 👇 load library from node_modules
const lodash = require("lodash");
// 👇 load your local exported modules
const { greetings } = require("./helper");
But even when you are running the code using Node, you may still see the require is not defined error because of your configurations.
Here’s the error logged on the console:
$ node index.js
file:///DEV/n-app/index.js:1
const { greetings } = require("./helper");
^
ReferenceError: require is not defined
If this happens to you, then the first thing to do is check your package.json file.
See if you have a type: module defined in your JSON file as shown below:
{
"name": "n-app",
"version": "1.0.0",
"type": "module"
}
The module type is used to make Node treat .js files as ES modules. Instead of require(), you need to use the import/export syntax.
To solve the issue, remove the "type": "module" from your package.json file.
Using .mjs extension when running Node application
If you still see the error, then make sure that you are using .js extension for your JavaScript files.
Node supports two JavaScript extensions: .mjs and .cjs extensions.
These extensions cause Node to run a file as either ES Module or CommonJS Module.
When using the .mjs extension, Node will not be able to load the module using require(). This is why you need to make sure you are using .js extension.
Conclusion
The JavaScript environment is the platform or runtime in which JavaScript code is executed.
This can be a web browser, a Node.js server, or other environments such as embedded systems and mobile devices.
The require function is not available by default when you run JavaScript from the browser, so ReferenceError: require is not defined is shown as the response.
Even when you run JavaScript code from Node.js, you can still see this error if you don’t set the proper configuration.
The solutions provided in this article should help you solve this error in both server and browser environments.
I’ve also written several other common JavaScript errors and how to fix them:
- How to fix JavaScript unexpected token error
- How to fix JavaScript function is not defined error
- Fixing JavaScript runtime error: $ is undefined
These articles will help you become better at debugging JavaScript errors.
Cheers! 🙏
This Javascript error is caused by using the Node.js global function require() in the browser. Since Node.js is a back-end technology, its module system won’t work in the browser. To get around this, you can use the require.js library or simply not use the require keyword and just define your <script> tags in the correct dependency order. You can also use Javascript modules (import and export) instead.
If you’re used to using Node.js on the back-end of your website and aren’t very familiar with front end development, you might accidentally use require() in the browser. This is a no-no. That’s because require() isn’t actually part of the Javascript standard, it’s actually just a Node thing.
Node defines modules with the exports.whatever = (your thing goes here) and require('your thing') syntax. This can get confusing when going back and forth between back-end Javascript code and front-end Javascript code.
In the browser there’s still such things as “modules”, but the syntax is different; it uses import and export instead. Which, in my opinion, is much less confusing. But it’s not up to me.
Let’s fix your code!
❌ Problem: you are using require() in the browser
We already knew this. This is the one and only cause of this error. If you’re using require() on the front-end you’re (usually) gonna have a bad time.
Let’s take a look at an example project. Here’s our file structure:
. ├── foo.js ├── index.html └── main.js
As you can see, we only have 3 files: an index.html file – we all know what that’s for. Then we have main.js and foo.js, both of which will be referenced from the index.html file.
Speaking of, here’s the index.html file below:
<!doctype html>
<html>
<head>
<title>My cool webpage</title>
</head>
<body>
<h1>Welcome to my webpage</h1>
<p>This is some text on my webpage</p>
<script src="foo.js"></script>
<script src="main.js"></script>
</body>
</html>
Most of this is just boilerplate junk we need in order to show you how this error works. The important lines are the <script> tags; those contain our Javascript that is causing the error.
The first one of those that we’ll look at is “foo.js”:
function saySomething() {
console.log("something");
}
exports.saySomething = saySomething;
In this file, we define a function called saySomething() using Node.js’s exports syntax. All saySomething() does is prints the word “something” out to the browser’s dev console. Not much to this one.
const foo = require('./foo');
foo.saySomething();
Above is the contents of main.js. This is the file that will be trying to use what’s in foo.js. Here, again, we’re using the Node.js module syntax to import or require() the contents of foo.js to be used. Then we attempt to use it. But, we’ll never get that far, because this is all sorts of wrong already.
Here’s what you’ll see in your dev console if you try to view this page in the browser:

As you can see, we get a couple errors here
exportsisn’t a thing on the front end, sofoo.jsthrew an error about thatrequirealso isn’t a thing, andmain.jsthrew an error for that as well
So none of this is going to work. Now what?
✅ Fix 1: don’t do that
That’s right. Just don’t bother with require or exports on the front-end. If you’re using some node module and its causing this, chances are it’s not meant to be used in the browser. If it is, you probably need to use something like webpack to bundle all the requirements up into a single file before you can use it in the browser.
For reference, here’s our index.html file (no changes):
<!doctype html>
<html>
<head>
<title>My cool webpage</title>
</head>
<body>
<h1>Welcome to my webpage</h1>
<p>This is some text on my webpage</p>
<script src="foo.js"></script>
<script src="main.js"></script>
</body>
</html>
Notice that foo.js is imported before main.js. This is important because main.js uses foo.js, so foo.js must be loaded first.
Next we’ll look at foo.js to see what changed:
function saySomething() {
console.log("something");
}
The only thing we did differently here is we got rid of the exports line. Again, that’s just a Node.js thing, and it’s not going to work in the web browser.
This is all we need to do in main.js, just call the function. This is because when you load scripts with the <script> tag in the browser, all the stuff in the file you reference gets dumped into the global namespace of the browser’s Javascript engine.
✅ Fix 2: use the requirejs library
If you absolutely must use require(), you might want to look at the requirejs library. Now, this predates the modern way of doing things via import and export (which I highly recommend you do instead), but requirejs still works.
Here’s our new index.html:
<!doctype html>
<html>
<head>
<title>My cool webpage</title>
</head>
<body>
<h1>Welcome to my webpage</h1>
<p>This is some text on my webpage</p>
<script data-main="main" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
</body>
</html>
Note the new syntax for the <script> tag, and also note that there’s only one of them. This is because requirejs will do all the importing of things for us. This prevents us from having multiple <script> tags junking up our HTML, and also makes sure stuff gets loaded in the correct order every time. The data-main property up there just takes the name of your “main” script, i.e. the one that you want to execute.
The src here is a content delivery network (CDN) link to requirejs. You can also download it from their official site here: https://requirejs.org/. CDNs are faster though, so you probably want to use cdnjs like I did above unless you have a good reason not to.
require(["foo"], function(foo) {
foo.saySomething();
});
Above is the contents of the main.js file now. It’s using requirejs‘s require() syntax, which is much different from Node.js require(). Here, we have to provide a list of required modules as the first argument, and the function that uses them (as well as the module itself as an argument to that function). The code that requires it goes in the callback.
define([], () => {
const module = {
saySomething: () => console.log("something")
}
return module;
});
Above is what’s in the foo.js file now. It also uses requirejs‘s special syntax, but this time for defining stuff that can be require‘d elsewhere. You just have to return an object with all the stuff you want to export hanging off of it. In our case, we have saySomething as a property of module, which gets returned by define()‘s callback.
Now, requirejs will get the job done, but it’s outdated given recent advancements in front-end web design. If you want to take a modular approach to your front-end code, you should probably go with the new natively supported module syntax, i.e. import and export.
But how do we do that?
✅ Fix 3: use Javascript modules instead (recommended)
This is the new way of doing things. Rather than give a long winded explanation of what it is, I’ll just show you the code.
index.js
<!doctype html>
<html>
<head>
<title>My cool webpage</title>
</head>
<body>
<h1>Welcome to my webpage</h1>
<p>This is some text on my webpage</p>
<script src="foo.js" type="module"></script>
<script src="main.js" type="module"></script>
</body>
</html>
Important thing to note here is type="module". That’s what lets you use import and export.
foo.js
export default function saySomething() {
console.log("something");
}
main.js
import saySomething from './foo.js' saySomething()
And there you have it. That’s how you should be doing modules on the front-end.
Conclusion
In this article, we covered what causes “Uncaught ReferenceError: require is not defined” and how to fix it. The most common cause, and the only one I’m aware of, is using require() in the front-end (in the web browser). The most important concept is that require() isn’t a thing outside of Node.js, which means you can’t use it in your front-end code without a 3rd party library like requirejs. Even then, the syntax is very different, and you should probably be using the official Javascript modules syntax of import and export, which you’ll be familiar with if you’ve ever used webpack.
That’s all for now, hope it helps!
When Node.js first came out in 2009, the dream of JavaScript everywhere finally became a reality for many JavaScript developers. Full-stack web developers can effectively use the same programming language for both their front and back end work which is huge for developer efficiency and the developer experience overall.
Tech stacks such as MEAN and MERN have further increased the popularity of using JavaScript literally everywhere. While writing your JavaScript code in the frontend is very similar to the backend, there are subtle differences that can create problems. One such problem is receiving the ReferenceError: require is not defined exception.

The Problem
While overwhelmingly similar, client-side and server-side JavaScript does have its differences. Most of these differences stem from the innovation needed to allow JavaScript to run in a non-browser environment. In Node.js, require is a function that is available to use JavaScript modules elsewhere. The syntax for using require is defined by the CommonJS specification which you can learn more about here. By contrast, client-side JavaScript supports the ES6+ specification for using modules via import and export.
The Solution
Your ReferenceError: require is not defined likely has one of two causes:
- You tried using
requirein a browser environment - You are in a Node.js environment but your project has
"type": "module"in itspackage.json
Let’s go over solutions for each possible cause.
You tried using require in a browser environment
Using require is not supported by JavaScript in the browser so you will need to replace it or find a way to make that work such as using Browserify. The choice is ultimately yours but the most simple solution is to just use the ES6 module syntax instead of require. What’s the difference? In the ES6 syntax you use import rather than require and you use export in the module itself. For example let’s say you have some code setup similar to this:
Code language: JavaScript (javascript)
// math.js function add(a, b) { return a + b; } // named export module.exports = { add, }; // subtract.js function subtract(a, b) { return a - b; } // default export module.exports = subtract; // main.js const { add } = require("./math"); // named import const subtract = require("./subtract"); // default import console.log(add(1, 2)); console.log(subtract(1, 2));
Here is that same example using ES6 import and export module syntax:
Code language: JavaScript (javascript)
// math.js // named export export function add(a, b) { return a + b; } // subtract.js function subtract(a, b) { return a - b; } // default export export default subtract; // main.js import { add } from "./math"; // named import import subtract from "./subtract"; // default import console.log(add(1, 2)); console.log(subtract(1, 2));
It should be noted that in both examples, you can name the default import anything you want. In this case, that means you could use the subtract function import like this to the same effect:
Code language: JavaScript (javascript)
// main.js import foo from "./subtract"; console.log(foo(1, 2));
Additionally, in the subtract.js module above, you can use export default on anonymous functions as well:
Code language: JavaScript (javascript)
// subtract.js export default function (a, b) { return a - b; }
You are using require in a Node.js environment
In this case, check your package.json file for an property called type. If that is set to module, ES6 modules will be enabled and you will run into the error mentioned above (specifically ReferenceError: require is not defined in ES module scope, you can use import instead). Simply remove that entry and you will be able to use require.
Conclusion
To recap, require is a keyword that is only supported in a Node.js environment using the CommonJS module syntax. In browser environments, modules use ES6 syntax with import and export. There are workarounds for each scenario but the simplest approach is to stick to the syntax that is supported in the environment you are currently using. Now that you have your modules set up accordingly, you can get back to enjoying JavaScript everywhere.
A common error you’ll run into, especially when transitioning from writing JavaScript in the Node runtime to writing JavaScript in the browser, is «Uncaught ReferenceError: require is not defined«. The two environments have different ways of importing modules, so trying to import code in the browser like you would in Node results in this error.
However, this isn’t the only time you might run into this error. Here are the various ways you might run into it:
- You try to use the
requirestatement in the browser - You try to use
requirein Node when ES modules are specified inpackage.jsonvia"type": "module" - You’re trying to use
requirein a file ending in.mjs, which typically specifies ES modules
Node
If you encounter this error in a Node environment, you’ve likely either specified to use ES modules via package.json or via the command line.
In case it is specified in package.json, you can fix this by removing the following line in the file:
{
"type": "module"
}
If you specified to use ES modules via the command line with --eval, you can fix this by removing the --input-type parameter from the command line call.
Browser
The require method is not available in the browser. To solve this, you have a few options, a few of which we’ll briefly describe here.
You can use a bundler like Webpack, which compiles your JavaScript code into a format that is compatible with the browser. Internally, a bundler like this would remove the require statement and instead merge the code into a single file. In some cases, some bundlers may even convert your require calls to import since that is supported by most browsers.
Another option is to just use ES modules, which is natively supported by most browsers. In order to use this, you’ll need to convert all of your require statements to import statements. You’ll also need to explicitly specify the type of the module in the <script> tag, like this:
<script type="module" src="./app.js"></script>
How you choose to fix this may depend on personal preference, if you’re using a bundler, etc.
- Version:v12.18.0
- Platform:Linux dev 5.3.0-53-generic V8 upgrades and what they mean for versioning #47~18.04.1-Ubuntu SMP Thu May 7 13:10:50 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
- Subsystem:require
What steps will reproduce the bug?
- Download LTS 12.18.0 from https://nodejs.org/dist/v12.18.0/node-v12.18.0-linux-x64.tar.xz
- Untar compressed file
- Save a js file with the following code: (Let’s called it test.js)
console.log(require) - Run //node-v12.18.0-linux-x64/bin/node test.js
- Node returns error output stating that require is not defined.
How often does it reproduce? Is there a required condition?
All the time.
What is the expected behavior?
The behavior should be similar to node executing the same one liner in REFL interactive shell.
$ node
Welcome to Node.js v12.18.0.
Type ".help" for more information.
> console.log(require)
[Function: require] {
resolve: [Function: resolve] { paths: [Function: paths] },
main: undefined,
extensions: [Object: null prototype] {
'.js': [Function],
'.json': [Function],
'.node': [Function]
},
cache: [Object: null prototype] {}
}
What do you see instead?
$ node test.js
(node:13608) ExperimentalWarning: The ESM module loader is experimental. file:///somedirectory/test.js:1 console.log(require); ^ ReferenceError: require is not defined
Additional information
The issue does not happen in older node versions. See text output below
$ node --version
v8.10.0
$ node test.js
{ [Function: require]
resolve: { [Function: resolve] paths: [Function: paths] },
main:
Module {
id: '.',
exports: {},
parent: null,
filename: '/somedirectory/test.js',
loaded: false,
children: [],
paths:
[ '/somedirectory/node_modules',
...,
...,
'/node_modules' ] },
extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
cache:
{ '/somedirectory/test.js':
Module {
id: '.',
exports: {},
parent: null,
filename: '/somedirectory/test.js',
loaded: false,
children: [],
paths: [Array] } } }
Require not defined javascript: The “ReferenceError: require is not defined” error can arise for several reasons:
- When we use the require() function in a browser environment.
- When we use the require() function in a Node.js project, where type is set to module in the
package.jsonfile. - When we use the require() function in Node.js, where files have a .mjs extension.
Use the ES6 module import and export syntax to resolve the “ReferenceError need is not defined” error.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- Write your HTML elements here -->
<!-- adding type as module in the script -->
<script type="module" src="index.js"></script>
<script type="module" src="anotherFile.js"></script>
</body>
</html>
- Now we can use the ES6 imports/exports syntax in
index.jsandanotherFile.js. - The index.js file exports a variable and a function.
index.js:
// Create a default export function say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
// Returns the multiplication result of the passed two numbers
return x * y;
}
// This is named export
export const id = 50;
Now we import the above index.js file into another file and can be accessed there.
index.js:
// Here we are importing the default and named export from the
// index.js file using the import keyword
import multiply, {id} from './index.js';
// Passing two numbers as arguments to the multiply() function
// (of index.js file) to get the multiplication of two numbers and
// print the result
console.log(multiply(3, 4)); // Output => 12
// Printing the 'id' variable value (of index.js file)
console.log(id); // Output => 50
Output:
12 50
NOTE:
Please keep in mind that each file can only have one default export. In the browser, use this syntax (ES6 Modules) rather than the 'require()' function.
Alternatively, you can insert the index.js file’s script above the anotherFile.js file’s script, and the function and variables from the index.js file will be made available to anotherFile.js without exporting and importing them.
Here’s an example that doesn’t include any imports or exports.
index.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!--Here the index.js file is loaded first, hence we can use the functions of it in anotherFile.js file-->
<script src="index.js"></script>
<script src="another-file.js"></script>
</body>
</html>
The index.js file just defines a function and a variable.
index.js:
// Create a default export function say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
// Returns the multiplication result of the passed two numbers
return x * y;
}
// This is named export
export const id = 50;
We can now utilize the function and variable in our other code without even having to import them.
anotherFile.js:
// Passing two numbers as arguments to the multiply() function // (of index.js file) to get the multiplication of two numbers and // print the result console.log(multiply(3, 4)); // Output => 12 // Printing the 'id' variable value (of index.js file) console.log(id); // Output => 50
Output:
12 50
Fixing the ERROR
If the require() function of the server is not specified/defined, we have set the type attribute/property to module in our package.jsonfile, or all files that have an extension of .mjs instead of .js.
To resolve the “ReferenceError require is not defined” error, remove the type property from your package.json file if it is set to the module and rename any files with file.mjs extension to have file.js extension.
package.json:
{
// It should be removed if we want to use require
"type": "module",
// Write the rest of the code.....
}
You may also utilize the ES6 module syntax with the import and export keywords.
Set the type property in your package.json file to module if you wish to utilize the import/export syntax to import and export modules.
package.json:
{
// Here we must add this below one
"type": "module",
// Write the rest of the code.....
}
We must have to replace the require and module.exports syntax with the import and export keywords.
Let us see an example where we define a function and a variable, and then export the function as a default export and the variable as a named export.
index.js:
// Create a function(default export) say multiply which accepts
// two numbers as arguments and returns their multiplication result
export default function multiply(x, y) {
// Returns the multiplication result of the passed two numbers
return x * y;
}
// This is named export
export const id = 50;
Now we are importing them into anotherFile.js from the above index.js file
anotherFile.js:
// Here we are importing the default and named import from the
// index.js file using the import keyword
import multiply, {id} from './index.js';
// Passing two numbers as arguments to the multiply() function
// (of index.js file) to get the multiplication of two numbers and
// print the result
console.log(multiply(2, 10)); // Output => 20
// Printing the 'id' variable value (of index.js file)
console.log(id); // Output => 50
Output:
20 50
NOTE:
- As said earlier, please keep in mind that you can only use 1 default export per file.
- You cannot use the
require()function in combination with the ES6 Moduleimport/exportsyntax. You must use one or the other on a consistent basis.