JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to export constants in JavaScript?

JavaScript enables you to export a constant or multiple constants using the export keyword.

If you want to export individual constants, then write export at the beginning of their declaration.

index.js
export const WEBSERVER_PORT = 8080;

export const HOMEPAGE = "tutorialsandyou.com";

You can also export constants after they have been declared by writing all of them as an object.

index.js
const WEBSERVER_PORT = 1024;
const HOMEPAGE = 'tutorialsandyou.com';

export { WEBSERVER_PORT, HOMEPAGE };

Once constants are exported, you can import them using a named import.

app.js
import {WEBSERVER_PORT, HOMEPAGE} from './index.js';

console.log(WEBSERVER_PORT); //8080
console.log(HOMEPAGE); //tutorialsandyou.com

Note: These two different ways of exporting constants are known as named exports.

There is also another way of exporting constants, which is using default export. In default export, you write export default before the constant declaration. In a file, you can only have a single default export. If you try to use multiple default exports in a file, you will get an error.

app.js
export default const WEBSERVER_PORT = 8080;
//Error: You can't have more than 1 default export
export const HOMEPAGE = "tutorialsandyou.com";

Recommended Posts