ts-compile
is a tool for compiling non-modular typescript code into a modular or non-modular bundle file, and guarantee right dependency orders as much as possible.
For npm users:
npm install -g ts-compile
For yarn users:
yarn global add ts-compile
cd /YourProjectDir
ts-compile -p tsconfig.json -o built/bundle.js -m cjs
-V, --version # output the version number
-h, --help # output usage information
-w, --watch # compile in watch mode
-p, --project <path> # tsconfig file
-o, --bundleOutput <path> # output file
-m, --bundleModule [format] # export top-level names (format: "es6", "commonjs")
-g, --bundleGlobal [namespace] # export top-level names to a namespace
Create a config file tsconfig.json
:
{
"compilerOptions": {
"module": "none",
"target": "es6",
"declaration": true,
"outFile": "built/bundle.js"
},
"include": ["src"]
}
Create a typescript source file src/a.ts
:
class A extends B { }
Create another source file src/b.ts
:
class B { }
Compile with tsc
:
tsc -p tsconfig.json
Will see caution:
src/a.ts:1:17 - error TS2449: Class 'B' used before its declaration.
Output:
// built/bundle.js:
class A extends B {
}
class B {
}
// built/bundle.d.ts
declare class A extends B {
}
declare class B {
}
Class A precede class B, that will cause a runtime error.
Compile with ts-compile
ts-compile -p tsconfig.json -o built/bundle.js
Output:
// built/bundle.js
class B {
}
class A extends B {
}
// built/bundle.d.ts
declare class A extends B {
}
declare class B {
}
Class B precede class A, no runtime error.
Compile into a module with ts-compile
ts-compile -p tsconfig.json -o built/bundle.js -m cjs
Output:
// built/bundle.js
class B {
}
module.exports.B = B;
class A extends B {
}
module.exports.A = A;
// built/bundle.d.ts
export declare class A extends B {
}
export declare class B {
}
Class B precede class A, no runtime error.
It's worth to mention that vscode will claim error TS2449
, if the compiler option outFile
in tsconfig.json
is set, so it's better to leave it unset, and execute ts-compile
with option --output
.