Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inlining Modules In Typescript

I would like to use modules in TypeScript for inlining purposes. For example, if I have this code in mymodule.ts:

export class mymodule {
    constructor() {
        console.log('Hi');
    }
}

When I include this class in another file with:

import { mymodule } from './mymodule.ts'

I would like to have the mymodule class copy-and-pasted or inlined to compiled file. I am using outFile option to compile to single file but it just creates multiple modules in one file, generating unnecessary wrapper codes. Is there a way to accomplish this?

Thanks.

like image 485
MehmetOguzDerin Avatar asked May 11 '26 19:05

MehmetOguzDerin


2 Answers

Let's start with JavaScript

Rollup does what you need but with JavaScript.

For example, here is a class:

// MyClass.js
export class MyClass {
    constructor() {
        console.log('Hi');
    }
}

And the entry point:

// main.js
import { MyClass } from './MyClass';
export const inst = new MyClass();

Then, install Rollup and run it:

npm install rollup
./node_modules/.bin/rollup main.js --o bundle.js --f es

Rollup produces the following file:

class MyClass {
    constructor() {
        console.log('Hi');
    }
}

const inst = new MyClass();

export { inst };

Try it here.

With TypeScript

There are two solutions:

  1. Use tsc to compile each TypeScript file to a JavaScript file, then use Rollup (this is what I do);
  2. Or, use a plugin for Rollup.

Regarding the second solution, since the official Rollup plugin use a legacy version of TypeScript, I suggest to give a try to rollup-plugin-typescript2.

If you use a Rollup plugin, then a configuration file for Rollup (rollup.config.js) will be required.

like image 184
Paleo Avatar answered May 13 '26 22:05

Paleo


What you're looking for is called scope hoisting, and there is no way (at the moment) to do it with the Typescript compiler alone. You will need to use Typescript + Rollup/Webpack in order to achieve that.

The gist is you need to modify your tsconfig.json to output ES2015 modules, which you will then pass to the bundler of your choice to combine them into a single file.

Note, in Webpack scope hoisting is performed by the ModuleConcatenationPlugin, which is only included for production builds by default.

like image 38
caseyWebb Avatar answered May 13 '26 21:05

caseyWebb



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!