Option 1 - if you are not using modules
If your code contains only regular Typescript, without modules (import/export) you just need to add parameter outfile
to your tsconfig.json
.
// tsconfig.json
{
"compilerOptions": {
"lib": ["es5", "es6", "dom"],
"rootDir": "./src/",
"outFile": "./build/build.js"
}
}
But this option have some limitations.
If you get this error:
Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'
Try "Option 2" below.
Option 2 - using a module loader
If you are using modules (import/export), you will need a module loader to run your compiled script in the browser.
When you compile to a single file (using outFile
), Typescript natively supports compiling to amd
and system
module loaders.
In tsconfig, you need to set module
to amd
or system
:
// tsconfig.json
{
"compilerOptions": {
"module": "AMD",
"lib": ["es5", "es6", "dom"],
"rootDir": "./src/",
"outFile": "./build/build.js"
}
}
If you choose AMD, you need to use the require.js
runtime. AMD requires an AMD loader, require.js is the most popular option (https://requirejs.org/).
If you choose System, you need to use the SystemJS module loader (https://github.com/systemjs/systemjs).
Option 3 - use a module bundler / build tool
Probably, the best option is to use a module bundler / build tool, like Webpack.
Webpack will compile all your TypeScript files to a single JavaScript bundle.
So, you will use webpack
to compile, instead of tsc
.
First install webpack, webpack-cli
and ts-loader
:
npm install --save-dev webpack webpack-cli typescript ts-loader
If you are using webpack with Typescript, it's best to use module
with commonjs
:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "es6", "dom"],
"rootDir": "src"
}
}
Webpack webpack.config.js
example:
//webpack.config.js
const path = require('path');
module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: {
main: "./src/YourEntryFile.ts",
},
output: {
path: path.resolve(__dirname, './build'),
filename: "[name]-bundle.js" // <--- Will be compiled to this single file
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: "ts-loader"
}
]
}
};
Now, to compile, instead of executing using tsc
command, use webpack
command.
package.json
example:
{
"name": "yourProject",
"version": "0.1.0",
"private": true,
"description": "",
"scripts": {
"build": "webpack" // <---- compile ts to a single file
},
"devDependencies": {
"ts-loader": "^8.0.2",
"typescript": "^3.9.7",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12"
}
}
Webpack's TypeScript Documentation
Lastly, compile everything (under watch mode preferably) with:
npx webpack -w