The outFile
option in the tsconfig.json file is only available if you set
the module
option to system
or amd
.
As described in "Code Generation for Modules", only
modules created for system
or amd
can
be simply concatenated together while keeping the same functionality.
That means, if you are using a different module system, then you could migrate all you files into AMD modules (or SystemJs), otherwise bundling is not possible with tsc
, and you would have to use a different solution for bundling.
What is "bundling" with tsc
tsc
can "bundle" files together, but only by simply concatenating them.
I assume they provide that functionality only because it's very easy to do.
But in order to bundle e.g. CommonJs files, the files would have to be transpiled into something completely
different, e.g. wrap each file into an individual scope, removing the module.exports
and create
the appropriate relations between the scopes, ... That is hard work to do, and there are other libraries
that are specialized into doing it.
Why AMD modules do work
E.g. AMD works by defining modules by calling the function define( myModule )
. These function calls can simply be concatenated, like:
module 1:
define( { x: 1, y: 2 } );
module 2:
define( function(){ return { hello: 'world' }; } );
Can be just concatenated to:
define( { x: 1, y: 2} );
define( function(){ return { hello: 'world' }; } );
and would still run in the same way. Similar with SystemJs.
Why CommonJs modules don't work
CommonJs modules on the other hand look like this:
module 1:
module.exports = { x: 1, y: 2 };
module 2:
module.exports = ( function(){ return { hello: 'world' }; } )();
When simply concatenated, the bundle would look like this:
module.exports = { x: 1, y: 2 };
module.exports = ( function(){ return { hello: 'world' }; } )();
That obviously doesn't work, because module.exports
would be overwritten repeatedly.
Other module systems would cause similar or worse difficulties.
How to bundle OR use modules
You can bundle, but not use modules:
You can make tsc
bundle your files, but if they use CommonJs modules, then the javascript just wouldn't work.
Therefore tsc
prints a warning if you state module: commonjs
. If your files don't contain conflicting code, then your code will run fine anyway, but then you don't need the module: commonjs
setting.
E.g. these settings in your tsconfig.json
would output the concatenated (but not working with CommonJs modules) bundle.js
file:
"moduleResolution": "nodenext",
"outFile": "./dist/bundle.js",
// "module": "CommonJS", <-- DON'T set the `module` property
You can use modules, but not bundle:
You can make tsc
keep the functionality of the CommonJs modules, but then e.g. the module.exports
assignments need to be kept separate:
tsconfig.json
:
"moduleResolution": "nodenext",
// "outFile": "./dist/bundle.js", // <-- DON'T set the `outFile` property
"module": "CommonJS",