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.
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.
There are two solutions:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With