How to Import Modules in TypeScript

David Mbochi Njonge Feb 02, 2024
  1. Create a TypeScript Project
  2. Use the export Keyword in TypeScript
  3. Use the import Keyword in TypeScript
  4. Export and Import a Single Object in TypeScript
  5. Export and Import Multiple Objects in TypeScript
  6. Conclusion
How to Import Modules in TypeScript

When learning to develop applications using TypeScript, we usually create very simple programs that often have no dependencies on each other.

For example, a program to log a message to the console is only one line and is contained in one file. However, production-grade applications contain multiple files, and these files contain code that has dependencies.

The developer can implement these dependencies or acquire them from a third-party library using the TypeScript modules. The TypeScript documentation defines a module as any file that contains a top-level import or export.

Any file that does not contain a top-level import or export means that the code is not accessible outside the file; otherwise, the scope of the code is global.

Create a TypeScript Project

Open WebStorm IDEA and select File > New > Project. On the window that opens, select Node.js on the left side and on the window that opens on the right side labeled New Project, change the project name from untitled to typescript-modules on the project Location section.

Finally, press the button labeled Create to generate the project. Once the window opens, open a new Terminal window by selecting View > Tool Windows > Terminal or the keyboard shortcut Alt+F12.

Use the following command to create a tsconfig.json file for the application.

~/WebstormProjects/typescript-modules$ tsc --init

Once your file has been generated, ensure the configuration in the file is as shown below. We can also copy and paste the configuration into the tsconfig.json file.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noEmitOnError": true

    }
}

Use the export Keyword in TypeScript

Create a file named EmailService.ts under the typescript-modules folder and copy and paste the following code into the file.

export class User{
    constructor(private name: String) {
        this.name = name
    }

    public toString(): String{
        return this.name
    }

}

export class EmailService {
    sendEmail(to: User,
              from: User,
              message: String): String {
       return `message: ${message} from: ${from} to: ${to}`;
    }
}

In this file, we have created two classes named User and EmailService, respectively. The sendEmail() method simulates the action of sending an email.

The sendEmail() method uses the User class to represent the user sending and receiving the email’s message. Since we want the classes to be accessible outside the file, we have prefixed each class with the export keyword.

Use the import Keyword in TypeScript

Create a file named Main.ts and copy and paste the following code into the file.

import {User, EmailService} from "./EmailService"

function main(){
    let thisService = new EmailService();
    console.log(thisService.sendEmail(
        new User("john"),
        new User("doe"),
        "Happy Birthday"));
}
main();

In this file, we have created a function named main() that logs the string returned by the sendEmail() method to the console.

The method accepts three parameters: to, from, and message and notes that the first two parameters are of type User.

To run this code, use the steps mentioned in this tutorial to open a new terminal window, copy and paste the following command into the terminal, and press Enter.

~/WebstormProjects/typescript-modules$ tsc && node Main.js

This command transpiles the TypeScript files to JavaScript files and executes the Main.js file using the node runtime environment. Ensure the output of the application is as shown below.

message: Happy Birthday from: doe to: john

Export and Import a Single Object in TypeScript

Create a file named User.ts and cut the User class in the EmailService.ts file to the user file. Modify the code in the user file to be as shown below.

class User{
    constructor(private name: String) {
        this.name = name
    }

    public toString(): String{
        return this.name
    }

}

export = User

In this code, we removed the export keyword from the class declaration and defined it using the export = User statement after the class declaration. This shows that we are exporting a single object from this module which is a class.

Since we also want the EmailService to export a single object, remove the export keyword from the class and add it after the class declaration, as shown below.

import User = require("./User");

class EmailService {
    sendEmail(to: User,
              from: User,
              message: String): String {
       return `message: ${message} from: ${from} to: ${to}`;
    }
}

export = EmailService

Since the EmailService class uses the User object, we have to import it to the class using the require() function. Note that this is how we import a single object from a module.

Another point to note is that with this import approach, we can directly invoke the class using the new keyword as the object being imported is a class, and the same applies to functions, interfaces and others.

To test whether the changes we have made are working as expected, we will reuse the Main.ts file with a few minor changes to the import statements, as shown below.

import EmailService = require("./EmailService")
import User = require("./User")

function main(){
    let newService = new EmailService();
    console.log(newService.sendEmail(
        new User("john"),
        new User("doe"),
        "Happy Birthday"));
}
main();

The only changes we have made in this file are using the require() function to import the single objects from the User.ts module and EmailService.ts module.

Run the application using the same command we used in the previous example and ensure the output is as shown below.

message: Happy Birthday from: doe to: john

Export and Import Multiple Objects in TypeScript

Modify the previous examples to use the export and import statements as we did in the first example. Remove the single object export and import in all three files that include EmailService.ts and User.ts.

Ensure the code for the two files is as shown below.

User.ts:

export class User{
    constructor(private name: String) {
        this.name = name
    }

    public toString(): String{
        return this.name
    }

}

EmailService.ts:

import {User} from "./User";

export class EmailService {
    sendEmail(to: User,
              from: User,
              message: String): String {
       return `message: ${message} from: ${from} to: ${to}`;
    }
}

Create a file named AllExports.ts under the typescript-modules folder and copy and paste the following code into the file.

export * from "./EmailService"
export * from "./User"

In this file, we are re-exporting all the member classes, interfaces, and functions exported in both the EmailService.ts and User.ts files. Note that we are exporting classes in this file since the module contains only class declarations.

We will use this module to import all the modules declared into the Main.ts file using a single import statement. To achieve this, ensure the Main.ts file code is as shown below.

import * as emailManager from "./AllExports"

function main(){
    let newService = new emailManager.EmailService();
    console.log(newService.sendEmail(
        new emailManager.User("john"),
        new emailManager.User("doe"),
        "Happy Birthday"));
}
main();

Note how we import all the modules defined in the AllExports.ts file using the syntax * as. The asterisk * tells the compiler to import all the exports in the file, while the as keyword creates a custom object name for imported exports.

We invoked the object using the new keyword in the previous examples. However, this will not work in this example.

To access the member details of the object, we need to use the object’s dot . operator to access them, which in our case are the EmailService and User classes.

If we try to use the new keyword on the emailManager object, we get the warning This expression is not constructable. Run this code and ensure the output is as shown below.

message: Happy Birthday from: doe to: john

Conclusion

This tutorial taught us how to work with modules in TypeScript. The topics covered include using the export and import keywords and exporting and importing on single and multiple objects.

David Mbochi Njonge avatar David Mbochi Njonge avatar

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

LinkedIn GitHub

Related Article - TypeScript Import