ES6 Modules — Imports and exports

This will make it easier to understand the imports and exports in anglarjs 4 and ionic framework

sigu
podiihq
2 min readJun 6, 2017

--

Note that this is not an advanced user blog, its a quick start for someone who want to get a high level overview of what import and export in es6

A bit of history

Writing a big project was a pain in javascript as there was no ability to break down the code into pieces and tell one piece that it depends on the other so the solution was to have some automated tools that would concatenate the different files into one single javascript file. Then in came the commonjs and AMD (asynchronous module definition) which looked something like this:

Exporting in es6

export default 'bottles'; // the module exports a default string
export function empty(){ } // exports named function empty
export const pi = 3.14 // exports a constant

Whatever has been exported above can be imported into another file and used. Lets look at importing functions after which we can have a general discussion on export and import

Importing the exported values

We can import the specific named exports i.e empty and pi
import { empty, pi } from '..filepath/filename'

This creates variables empty and pi within the file scope (remember variable scopes) which can be used anywhere within the file e.g

radius = 34;
area = pi * radius * radius; // this is possible since pi has been exported and imported into this file

What if we exported the variable with a name but we want to use a different name in the import file? We use the as keyword for this to create an alias

import{empty, pi as piValue} from '../filepath/filename'; // now the variable name here will be piValue

What if we want to import the default that was exported too?

import bottles, {empty, pi} from '../filepath/filename';

We can also import all the exported variables using the wildcard character then set an alias which will namespace the variables. Have a look at this

import * as formBuilder from '../filepath/filename'; //imports every exported member from the file
console.log(formBuilder.pi) // console logs the pi value
console.log(formBuilder.empty)
By namespacing we mean you go through that name (formBuilder) to get to the variable

How this is used in angular4 and ionic

//example of exports which exports a class that contains a function
export class CommentsPage {
deleteComment() {console.log('deleted'}
}

Now to import

// examples of imports - showing other imports
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { CommentsPage } from '../../providers/comments';
class exampleClass{
console.log(CommentsPage.deleteComment())
// should output 'deleted'
}

References for more

  1. MDN exports
  2. MDN imports
  3. Amazing youtube video

--

--

sigu
podiihq

Software application developer, found new craze in functional programming.