TypeScript

TypeScript and ES6 import syntax

Posted on by  
Oliver Verver

When I started using TypeScript for my Angular applications, I was confused about all the different ways with which you could import other modules. import './polyfills.ts'; import { Component } from '@angular/core'; import HomeComponent from './pages/home/home-page.component'; import * as _ from 'lodash'; import assert = require('assert'); At first, I thought that as a programmer you could choose whether you wanted to use curly braces or not, but I quickly found out that that was not the case. It all depends on how the module that you are importing is structured. I have created an overview of the different ways by which a module can be exported, together with their corresponding import syntax. Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well. The examples are from my solution to the first puzzle of Advent of Code 2016 and can be found on GitHub if you want to play around with imports and exports yourself.

Export syntax

When a module needs to export multiple variables, it can use so-called named exports:

Another way that named exports can be done is by specifying what you want to export at the end of the module:

Import Syntax

You can import these modules in two ways. Either you import everything as one object (sometimes called namespace):

Or, you specify all the individual variables that you want to import:

If you specify the variables, you can also import them under a different name:

Continue reading →

shadow-left