Import and Export Statements in JavaScript and Use Them




Import and export statements are two nice options launched ES6 (ES2015). These two assertion means that you can export and import your code and use it everytime you want. This tutorial will present you what import and export statements are, how they work and easy methods to use them.

A fast introduction

Prior to now, when JavaScript developers needed to separate their code into modules they’d to make use of one of many three choices. These choices had been AMD, CommonJS and UMD. There was built-in assist for modules in JavaScript. Issues modified when the ES2015 (ES6) specification was launched.

One function this specification dropped at JavaScript was additionally a assist for modules on a language-level. JavaScript developers had been now in a position to work with native modules with the assistance of newly launched import and export statements. Now, you as a JavaScript developer can cut up your code into a number of information.

Every of those information is a module. These modules can include something, from variables and features to courses. With the intention to this code out there to the surface you must merely exporting it. Once you need to use a few of that exported code, you merely import it the place you want. Now, let’s check out each these new statements.

The export assertion

Once you need to export some variable, perform or class you must place the export key phrase earlier than it. This tells JavaScript two issues. First, you need that “factor” to be out there from the surface of the present file. Second, different components of this system ought to have the ability to import that “factor” with the import assertion.

Once you export some code you’ll be able to nonetheless change it and replace it. Nevertheless, you’ll be able to that solely on the place the place you exported it. You may’t try this whenever you import that exported code some place else. Once you import some exported code you’ll be able to solely learn it and use it, however not change it.

Two methods to export

Once you need to export some code with export assertion, there are two methods to do it. The primary one is by exporting in the mean time of declaration. On this case, you set the export assertion on the identical line proper earlier than the variable, perform or class you’re about to declare.

// Declare and export variables
export const MY_PASS = 'Some essential secret.'
export let title = 'Jack'
export var stack = 'JS'

// Declare and export features
export perform sayHi() {
  return 'Hello.'
}

export const sayBye = perform() {
  return 'Bye.'
}

export const sayGoodBye = () => {
  return 'Good bye.'
}

// Declare and export class
export class Individual {
  title = this.title
  age = this.age
  #my_secret = this.secret
}

The second strategy to export code is by declaring it first and exporting it after that. On this case, you utilize the export assertion adopted by the “factor” you need to export.

// Declare variables
const MY_PASS = 'Some essential secret.'
let title = 'Jack'
var stack = 'JS'

// Export variables
export MY_PASS
export title
export stack

// Declare features
perform sayHi() {
  return 'Hello.'
}

const sayBye = perform() {
  return 'Bye.'
}

const sayGoodBye = () => {
  return 'Good bye.'
}

// Declare and export features
export sayHi
export sayBye
export sayGoodBye

// Declare class
class Individual {
  title = this.title
  age = this.age
  #my_secret = this.secret
}

// Export class
export Individual

Once you determine to make use of the second approach there may be one other factor to do. As a substitute of export all these issues individually, you’ll be able to export them directly with a single export assertion. For instance, on the finish of the file. To do that, you must wrap the whole lot you need to export with curly braces, separated by commas.

// Declare some stuff
const MY_PASS = 'Some essential secret.'

let title = 'Jack'

perform sayHi() {
  return 'Hello.'
}

class Automotive {
  numOfWheels = this.numOfWheels
  typeOfFuel = this.typeOfFuel
}

// Export all of the stuff directly
export { MY_PASS, sayHi, Automotive }

Named and default export

There are additionally two sorts of exports you should use. One is known as named export and the opposite default export. Relating to named exports, you’ll be able to create as lots of them as you need. There isn’t a restrict. This doesn’t apply to default exports. In JavaScript, you’ll be able to have just one default export per module.

The primary kind, named export, is what you noticed on the examples above. In these examples, you had been utilizing the export key phrase together with the title of the factor you needed to export. All these exports had been named. Once you need to export one thing as default you must add default between the export assertion and what you need to export.

// Named export
export const LANG = 'English'

// or
const favoriteFantasy = 'Discworld'
export favoriteFantasy


// Default export
export default const LANG = 'English'

// or
const favoriteFantasy = 'Discworld'
export default favoriteFantasy

There may be one other strategy to export one thing as default. You may wrap the title of the factor you need to export with curly braces. Subsequent, you add as key phrase, adopted by the default key phrase. This may even export that factor as default.

// One other strategy to create default export
const FAVORITE_SEASON = 'Summer time'

// Export FAVORITE_SEASON as default
export { FAVORITE_SEASON as default }

Renaming exports

Once you export one thing, and also you don’t need to use the variable, perform or class title, you’ll be able to rename it. To do this, you must wrap the title with curly braces and add as key phrase adopted by new title, underneath which you need to export it. For those who export a number of issues, you should use this to rename all of them or simply some.

// Declare a variable
let sillyJoke = 'Knock, knock.'

// Export the variable and rename it
export { sillyJoke as classicJoke }


// Declare a number of variables
const petOne = 'Canine'
const petTwo = 'Cat'
const petThree = 'Alligator'
const petFour = 'Dragon'

// Export all variables and rename some
// Notice: line breaks are only for readability
export {
  petOne,
  petTwo as pet2, // rename export for petTwo
  petThree as pet3, // rename export for petThree
  petFour
}

Re-exporting exports

The very last thing you are able to do with export assertion some import issues and instantly export them once more. Throughout this course of you’ll be able to both maintain their names or rename them. The syntax for re-exporting is just like the syntax for importing. You’ll study that in a minute.

In case of re-exporting, you begin with the export assertion. What follows are curly braces with title of the module you need to export. That is adopted by from key phrase and title of the file from which that module is exported. If you wish to rename the exported module add as key phrase adopted by new title after the module title, contained in the curly braces.

// Re-export module
export { myExpModule } from './file.js'

// Re-export module and rename it
export { myExpModule as myRenamedExpModule } from './file.js'

You employ the identical syntax additionally whenever you need to re-export default export. In that case, between the curly braces goes “default” as an alternative of some module title. In any other case, you’ll be able to substitute that with * and omit the curly braces.

// Re-export default module
export { default } from './file.js'

// Various
export * from './file.js'

// Re-export default module and rename it
export { default as defaultRenamed } from './file.js'

The import assertion

Once you need to import some code you must use the import assertion. Do not forget that it will work solely with code you exported with the export assertion. You may’t import one thing you didn’t export. Once you need to import one thing, there are two choices from which you’ll select. We’ll get to that in a minute.

In each instances, you must begin the road with the import key phrase. Subsequent, you specify the title of the exported module you need to import. This a part of syntax will differ in line with which of the 2 choices you select. After that follows from key phrase, adopted by the title of the file from which you need to import these modules.

// Instance of import syntax
import { someModule } from 'file.js'
import someModule from 'file.js'

Named imports

The primary choice is to import modules, these belongings you’ve exported, individually. For those who select this, you must take into account the way you exported these modules. For those who exported these modules with named exports you must use precisely the names you used. For those who used renaming, then, you must use these new names.

When importing named exports, you must wrap these names with curly braces. That is required whenever you import named exports. Equally to exporting, it’s also possible to import all exports individually with a number of import statements. You can too import all of them with single import assertion. In that case, you must separate these exported modules with commas.

// File 1: file-one.js
// Declare and export some stuff
// Use named export
export const age = 29

perform sayHi() {
  return 'Whats up'
}

// Use named export with renaming
export { sayHi as greeting }


// File 2: file-two.js
// Import solely the "age" variable
import { age } from './file-one.js'

// Attempt to learn imported "age" variable
console.log(age)
// Output:
// 29


// Import solely the "greeting" perform
// Notice: you exported the sayHi as greeting
// so you must import it as greeting, not as sayHi
import { age } from './file-one.js'

// Import each, "age" and "greeting"
import { age, greeting } from './file-one.js'

// Attempt to learn imported "age" variable
console.log(age)
// Output:
// 29

// Attempt to name imported "greeting" perform
console.log(greeting())
// Output:
// 'Whats up'

Default imports

For those who exported some module as default, you’ll be able to select no matter title to import that module you need. And, don’t wrap the module title with curly braces if you wish to import default export. In any other case, JavaScript will throw an error. One vital factor. Once you import one thing as default, you don’t use the variable key phrase.

// File 1: file-one.js
// Declare and export some stuff as default
// Notice: omit the "const", "let" or "var" key phrases
export default surname = 'Joe'


// File 2: file-two.js
// Import solely default export "title"
// Notice: no curly braces across the title
import surname from './file-one.js'

// Attempt to learn imported "age" variable
console.log(surname)
// Output:
// 'Joe'

Once you export one thing as default, you don’t have to make use of the identical title to import it elsewhere. Once you use default export JavaScript is aware of that that file incorporates just one export. So, it is going to determine what you need to import even should you use totally different title to import that factor.

// File 1: file-one.js
// Declare and export some variable as default
export default secret = 'That is some essential secret.'


// File 2: file-two.js
// Import the default export utilizing a distinct title
import password from './file-one.js'

// Attempt to learn imported "age" variable
console.log(password)
// Output:
// That is some essential secret.

Importing named modules directly

The second choice is to import all of the stuff directly. Do not forget that it will import the whole lot you exported from the file you now need to import from. The syntax is just like importing particular person modules. The distinction is two-fold. First, you substitute the title of the module you need to import with * (asterisk).

Second, you must add as key phrase adopted by the title by which you need to entry these imported modules. This title could be something you need.

// File 1: file-one.js
// Declare and export some stuff
export const pets = ['Dog', 'Shark', 'Tiger']
export const currentlyReading = 'Snow Crash'
export perform add(a, b) {
  return a + b
}


// File 2: file-two.js
// Import the whole lot exported from file-one.js
import * as myStuff from './file-one.js'

// Attempt to learn the worth of imported "pets" variable
console.log(myStuff.pets)
// Output:
// ["Dog", "Shark", "Tiger"]

// Attempt to learn the worth of imported "currentlyReading" variable
console.log(myStuff.currentlyReading)
// Output:
// "Snow Crash"

// Attempt to name the imported add() perform
console.log(myStuff.add(89, 98))
// Output:
// 187

Renaming imports

Equally to the export assertion, import assertion additionally means that you can rename your imports. This may be helpful whenever you need to import some module, however you need to use it by a distinct title. The syntax just like the syntax for renaming exports. The one distinction is that you’ll substitute the export assertion with import.

// File 1: file-one.js
// Declare and export some stuff
export const transpiler = 'Babel'
export const language = 'JavaScript'
export const syntax = 'jsx'
export const framework = 'React'


// File 2: file-two.js
// Import modules exported from file-one.js
// and rename a few of these imports
// Notice: line breaks are once more only for readability
import {
  transpiler,
  language,
  syntax as fileExtension,  // rename export for syntax
  framework as library  // rename export for framework
} from './file-one.js'

// Attempt to learn the worth of imported "pets" variable
console.log(syntax)
// Output:
// "jsx"

// Attempt to learn the worth of imported "currentlyReading" variable
console.log(library  )
// Output:
// "React"

Importing particular person named exports and default export

One good factor about import assertion is that it might probably work with named and default exports on the identical time. So, should you used each, named and default exports in the identical file, you’ll be able to nonetheless import these modules individually with a single import assertion. To do that, there are two issues you must keep in mind.

First, you must import any default export with out wrapping it with curly braces. Second, you must wrap any remaining named exports with these curly braces. For those who import two or extra named exports, separate these exports with commas. Hold all of them nonetheless inside that one pair of curly braces.

// File 1: file-one.js
// Declare and export some stuff
export default tvShow = 'Breaking Dangerous'
export const mainCharacter = 'Walter White'
export const topic = 'Chemistry'
export const ranking = '9.5/10'


// File 2: file-two.js
// Import each named and default exports from file-one.js
// Notice: the default export "tvShow" needs to be first
// and out of doors of the curly braces
import tvShow, { mainCharacter, topic, ranking } from './file-one.js'

Dynamic imports

Now you already know about import and export statements and easy methods to use them. Nevertheless, the import assertion just isn’t the one strategy to import modules. There may be additionally another referred to as dynamic import. The principle distinction between the import assertion and dynamic import is that the import assertion is static.

Which means that whenever you import one thing with import assertion it will likely be imported in the mean time you run your code. For those who import some massive module, or numerous them, it might probably make your code slower. Dynamic import works in a different way. Dynamic imports are usually not loaded in the mean time you run your code.

Nicely, they’ll, however solely if you’d like that to occur. If not, you’ll be able to delay their load. You should use dynamic imports additionally to load issues solely underneath sure situation. If this situation by no means occurs that dynamic import is not going to be loaded. In that case, that extra module will logically don’t have any impact on the efficiency of your code.

Once you need to use dynamic import you utilize the import key phrase. Nevertheless, this time you name it as a perform, and move in path to the module as an argument. This perform will return a promise. You may then eat that promise with the then handler. The loaded module is handed to then handler by parameter.

As a substitute for the then() handler, it’s also possible to use await key phrase, and assign the module to a variable. Then, you are able to do no matter you need with that module.

// Instance of dynamic import
import('./my-module.js')
  // Use then() handler to eat returned promise
  .then((module) => {
    // Do one thing with the module
    // returned by the promise
    // and handed by "module" parameter
  })

// Various with await
(async perform() {
  // Assign the module to a variable
  const myModule = await import('./my-module.js')
  // Do one thing with that module
}())

If you wish to use await keep in mind that you must use async function. Nicely, until you utilize top-level await which is an alternative choice. In that case, no want to make use of async perform.

// Utilizing top-level await
// Assign the module to a variable
const myModule = await import('./my-module.js')
// Do one thing with that module

Conclusion: Import and export statements in JavaScript and easy methods to use them

Import and export statements are two options that may be very helpful. They may help you make your code clearer and simpler to handle and preserve. What’s extra, they’re each additionally very straightforward to be taught and use. I hope that this tutorial helped you study what import and export statements are, how they work and easy methods to use them.

For those who preferred this text, please subscribe so you do not miss any future put up.








If you would like to assist me and this weblog, you’ll be able to develop into a patron, or you should buy me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Import #Export #Statements #JavaScript