JavaScript(JS) import and export

In JavaScript, import and export are used to work with modules, which are a way of organizing code into separate files, each with their own scope and functionality.

The export statement is used to export functions, objects, or values from a module, making them available for use in other parts of the code. There are two types of exports: named exports and default exports.

Named exports are created by adding the export keyword in front of a variable, function, or class declaration, like this:

re‮ef‬r to:theitroad.com
// module.js
export const myVariable = 'some value';

export function myFunction() {
  // function code here
}

export class MyClass {
  // class code here
}

Default exports are created by using the export default statement before a variable, function, or class declaration, like this:

// module.js
export default function() {
  // function code here
}

export default class {
  // class code here
}

To import exports from a module, we use the import statement followed by the module name and the specific exports we want to use. For named exports, we enclose the name of the exported item in curly braces. For default exports, we use any name we want:

// main.js
import { myVariable, myFunction } from './module';

// or

import myDefaultExport from './module';

It's also possible to use the import * as syntax to import all of a module's exports under a single namespace:

import * as myModule from './module';

console.log(myModule.myVariable);
myModule.myFunction();