Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two classes in separate files into one ES6 module using TypeScript?

I have two files and every file I have a class:

//Hello.ts
export class Hello {
    private n: number = 100;
    private s: string = "Hi";
    public prints(s: string): void {
    console.log(s);
    }
}
//Foo.ts
import {Hello} from 'Hello'
export class Foo {
    public test(): void {
        let hello: Hello = new Hello();
    hello.prints("Hi");
    }
}

When I do tsc Hello.ts Foo.ts --target es6 --out module.js I get Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'. How to merge two classes in separate files into one ES6 module?

I opened issue asking to implement such feature, but I was said that it is supported already.


1 Answers

Re-exporting members

You can make the classes Foo and Hello accessible from a single module:

// main.ts
export { Hello } from "./Hello";
export { Foo } from "./Foo";

Now these classes are available from 2 modules: their original file, and main.

Using Rollup

Additionally, like Bergi suggests in a comment, you can use Rollup with a plugin for TypeScript: this one or this other.

Rollup takes several modules and produce one module with just the exports of the entry point module. You can test online with the REPL (using JavaScript syntax because the REPL hasn't the plugin for TypeScript).

like image 137
Paleo Avatar answered Sep 04 '25 22:09

Paleo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!