computer history timeline programming languages1604677346377387

JavaScript Step-by-Step Tutorial – Using Modules With Export and Import Keywords

Modules allow us to break JS code into separate files which can be exported, imported and reused. Modules were not available in Vanilla JS until ES6. Not all JS interpreters support Modules. All we have to do is to create a separate file and use export keyword into that. In order to learn about modules please follow this tutorial first. It will help you to set up a JS project in webpack. After setting up please create a new file math.js in the src folder with this code.

export const PI = 3.1415;
export const DEGREES_IN_CIRCLE = 360;
export function convertDegToRad( degrees ) {
  return degrees * PI / ( DEGREES_IN_CIRCLE /2 );
}

Here we are using the export keyword with every variable and function. But we can also use export one time. 

const PI = 3.1415;
const DEGREES_IN_CIRCLE = 360;
function convertDegToRad( degrees ) {
  return degrees * PI / ( DEGREES_IN_CIRCLE /2 );
}

export { PI, DEGREES_IN_CIRCLE, convertDegToRad }

Now we can use the import keyword in our index.js file to use these variables and functions.

import {PI} from '/src/math.js'
import {DEGREES_IN_CIRCLE} from '/src/math.js'
import {convertDegToRad} from '/src/math.js'

console.log(PI)
console.log(DEGREES_IN_CIRCLE)
console.log(convertDegToRad(30))

We can also export ES6 classes. Please create a new file user.js in the src folder with this code in it. 

export default class User { 
  constructor(name) {
    this.name = name;
  }
}

Now we can use the import keyword in index.js to use the User class.

import User from '/src/user.js'

const user = new User('John')
console.log(user.name)

When we are exporting classes we can also export and import classes this way. In user.js we need this code without the default keyword. 

export class User { 
  constructor(name) {
    this.name = name;
  }
}

And we can use the import keyword like this. 

import {User} from '/src/user.js'

const user = new User('John')
console.log(user.name)

But if we use the default keyword with class in user.js, we can import like this too. 

import MyUser from '/src/user.js'

const user = new MyUser('John')
console.log(user.name)