Skip to content

ES6 Imports/Exports

Video Lecture

Section Video Links
ES6 Imports/Exports ES6 Imports/Exports ES6 Imports/Exports 

Overview

On larger projects, it is common to split up your code into separate files. When doing this, you will need to tell each file which other file it needs to reference in case it is using objects, classes, types or interfaces from the other files.

Replace ./src/test.ts with this below, and create the other two files alongside also in the ./src/ folder

./src/test.ts

1
2
3
4
5
6
import { Cat, Dog } from './animals'

const CAT = new Cat('Cosmo', 8)
console.log(CAT.name)
const DOG = new Dog('Rusty', 12)
console.log(DOG.name)

./src/animals.ts

1
2
3
4
5
6
7
8
9
import Animal from './animal'

export class Cat extends Animal {
    constructor(name: string, age: number) {
        super(name, age)
    }
}

export class Dog extends Animal {}

./src/animal.ts

1
2
3
4
5
6
7
8
9
export default class Animal {
    name: string
    age: number

    constructor(name: string, age: number) {
        this.name = name
        this.age = age
    }
}

Re compile and execute,

tsc -p ./src
node ./dist/test.js

Outputs

Cosmo
Rusty

When looking at the code, you can see an import/export relationship. test.ts imports Animals which exports the Cat and Dog classes. Animals imports Animal which exports Animal.

test.ts and animals.ts can find their chosen imports, because all the classes Animal,Cat and Dog have all been marked as export throughout the files.

Note that I have used export default in the Animal class. This allows me to import it into the ./src/animals.ts by using import Animal from './animal'.

Whereas, I have exported the Cat and Dog classes using just the export keyword by itself. Which means that I need to import them using the curly braces, such as import { Cat, Dog } from "./animals";.

I could have split Cat and Dog into their own files as well and used the export default keywords, and then imported them separately without using the curly brace notation.

Note that you can only use export default once in any file, even if it has multiple exports. Try it by marking both Cat and Dog as export default and you will see the error,

A module cannot have multiple default exports.ts(2528)
animals.ts(3, 22): The first export default is here.

This is optional how you structure your files, if you want to mark exports as default or not. Throughout the design pattern examples, I will use both techniques to import/export.