Exports and Imports in JS

In modern JavaScript projects you can split the code across multiple JavaScript files and its called modules. By doing this, you can keep your code more focused and manageable.

To access the functionality in another file, you need to export (to make it available) and import(to get the access) statements.

There are two types of exports: defaults (unnamed) and named exports:

export default ..;
export const someInfo = ...;

As shown, below in the default exports you can choose the name to import but the named exports have to be imported by their name.

import someNameOfYourChoice from './path/to/file.js';

import { someInfo } from './path/to/file.js'; 

A file can only contain one default and an unlimited amount of named exports. You can also mix the one default with any amount of named exports in one and the same file.

When importing named exports, you can also import all named exports at once with the following syntax:

import * as nameOfYourChoice from './path/to/file.js'; 

nameOfYourChoice will bundle all exported variables/ functions in one JavaScript object. You can access the same by nameOfYourChoice.someInfo.

In the below example person.js you are exporting the person function as default. And in the utility.js you are exporting each functions seperatly.


const person = {
    name: "Bino"

export default person
export const clean = () => {
    //your code

export const baseData = 10;
import person from './person.js
import prsn from './person.js

import { clean, baseData } from './utility.js'

import * as bundled from './utility.js'

javascript info

Read More