Typescript compile to single file
Solution 1
This will be implemented in TypeSript 1.8. With that version the outFile option works when module is amd or system.
At this time the feature is available in the development version of Typescript. To install that run:
$ npm install -g typescript@next
For previous versions even if it's not obvious the module and the outFile options can not work together.
You can check this issue for more details.
If you want to output a single file with versions lower than 1.8 you can not use the module option in tsconfig.json. Instead you have to make namespaces using the module keyword.
Your tsconfig.json file should look like this:
{
"compilerOptions": {
"target": "ES5",
"removeComments": true,
"preserveConstEnums": true,
"outFile": "./build/build.js",
"sourceRoot": "./src/",
"rootDir": "./src/",
"sourceMap": true
}
}
Also your TS files should look like this:
module SomeModule {
export class RaceTrack {
constructor(private host: Element) {
host.appendChild(document.createElement("canvas"));
}
}
}
And instead of using the import statement you'll have to refer to the imports by namespace.
window.addEventListener("load", (ev: Event) => {
var racetrack = new SomeModule.RaceTrack(document.getElementById("content"));
});
Solution 2
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
Solution 3
The Easiest Way
You can do this with a custom tool called ncc, built and maintained by Vercel. Here's how they're using it in create-next-app:
ncc build ./index.ts -w -o dist/
Install it with yarn:
yarn add @vercel/ncc
Or npm:
npm install @vercel/ncc
Related videos on Youtube
David Limkys
Java & Javascript Programmer for a couple of years now, working in a COE team.
Updated on April 22, 2021Comments
-
David Limkys about 3 years
I'm using TS 1.7 and I'm trying to compile my project to one big file that I will be able to include in my html file.
My project structure looks like this:
-build // Build directory -src // source root --main.ts // my "Main" file that uses the imports my outer files --subDirectories with more ts files. -package.json -tsconfig.json
my tsconfig file is:
{ "compilerOptions": { "module":"amd", "target": "ES5", "removeComments": true, "preserveConstEnums": true, "outDir": "./build", "outFile":"./build/build.js", "sourceRoot": "./src/", "rootDir": "./src/", "sourceMap": true } }
When I build my project I expect the build.js file to be one big file compiled from my source. But ths build.js file is empty and I get all of my files compiled o js files.
Each of my TS files look a bit like this
import {blabla} from "../../bla/blas"; export default class bar implements someThing { private variable : string; }
What am I doing wrong ?
-
José Mancharo almost 3 yearsMy favorite way to accomplish this is with esbuild. It is written in go and therefore is much faster than TSC and 100x faster than webpack. See esbuild.github.io. It supports the outFile and outDir options.
-
-
David Limkys over 8 yearsThe issue that you pointed out seemed to be resolved, also github.com/Microsoft/TypeScript/wiki/Compiler-Options suggests that the --outFile flag as to be used with the --module flag.
-
toskv over 8 yearsindeed, but it does not seem to be working. :( Maybe make an issue out of it on github?
-
toskv over 8 yearsbtw, the resolutions of the issues on github do not seem to point to any actual changes to the code base, they always close with this being the default behaviour.
-
toskv over 8 yearsI just noticed this. It looks like the fix for the issue I mentioned will be available in version 1.8. Maybe use typescript@next to get the latest now? github.com/Microsoft/TypeScript/wiki/Breaking-Changes
-
toskv over 8 yearsAnd I can confirm this. if using typescript@next this works just fine. :) I'll edit my answer to include this too.
-
JMK over 8 years@toskv My module is set to commonjs and my output file is still empty, is this to be expected too?
-
toskv over 8 yearsif you are using typescript 1.7.5 (latest released) yes
-
toskv over 8 yearsit's just something that was never implemented. if you want to use it though you can get the development version of tsc. just run: npm install -g typescript@next
-
JMK over 8 yearsUnderstand now, sorry I'm a bit slow sometimes!
-
toskv over 8 yearsI edited the answer to include the @next part too, just so it's clearer. :)
-
Alex Zhukovskiy over 7 years@toskv and what if I want to compile each directory to its own file? For example I have
script/x/a.ts
,script/x/b.ts
,script/y/c.ts
,script/y/d.ts
,script/y/e.ts
and I want to getscript/x.js
andscript/y.js
. Now I'm addingtsconfig.json
in each folder which combines all script files into one, but I'm looking for more elegant solution, because I want to have only one singletsconfig.json
for such case. Is it possible at all? -
toskv over 7 yearsI could see that doable with something like gulp-typescript. with tsc alone you'll need a tsconfig in each folder that you want compiled separately (as far as I know).
-
vitaly-t almost 6 yearsIs there a better way to do this with TypeScript 3.x?
-
Alkis Mavridis over 4 yearsYour solution does not work. I get "Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'."
-
1valdis over 4 years@AlkisMavridis same for me. Did you find a solution?
-
Paul Razvan Berg about 4 years
-
Daniel Barral almost 4 years@AlkisMavridis I updated my answer with other options to compile to a single file, if you are using modules.
-
Philippe Fanaro over 3 yearsDon't forget to also install the CLI with
npm i webpack-cli
and neatly run Webpack on watch mode withnpx webpack -w
. -
JohnF over 3 yearsWhat file is that last one where I put 'scripts.build' to 'webpack'?
-
Daniel Barral over 3 years@JohnF That file is the "package.json" and is located at root directory. I updated the answer. docs.npmjs.com/creating-a-package-json-file
-
rambi about 3 yearsDoes this create a code that you can run directly in the browser ? My browser says that "__dirname" is not defined
-
Paul Razvan Berg about 3 yearsI don't know, but based on what you shared, the answer seems to be no.
__dirname
is a node.js-specific environment variable. -
Eric Burel almost 3 yearsncc is for Node.js project, eg if you want to build your database seeding scripts from TypeScript to JavaScript. Often those scripts are written "by hand" in JavaScript, with ncc you can instead reuse the code you have written in TypeScript for your app.
-
Matthew Ratzloff almost 3 years@rambi You can run it in the browser with a small hack. In your HTML file, add
var __dirname = "", module = {}
somewhere before the output fromncc
. It's probably easiest to do it in a separate script tag.