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.

export const WEBSERVER_PORT = 8080;

export const HOMEPAGE = "";

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

const WEBSERVER_PORT = 1024;
const HOMEPAGE = '';


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

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

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

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.

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

Recommended Posts