Roland Buergi
Roland Buergi

Reputation: 1199

Compiling TypeScript with RequireJs and Grunt into a single file

We are trying to optimize our TypeScript project consisting of many files by compiling it into a single, AMD capable, file using Grunt. We have researched all we could find on the internet but are still struggling to get a proper grip on the task. The compilation works fine as long as we do not use external imports, but as soon as we have references to external libraries, the process fails. Example:

  1. MyClass1.ts

    import jquery = require('jquery');
    export class MyClass1{
       //some code using jquery 
    }
    
  2. MyClass2.ts

    import jquery = require('jquery');
    export class MyClass2{
       //some other code using jquery 
    }
    

In this case, even when operating the TypeScript compiler using

 tsc --out singlefile.js ...

will actually not include the two files. Rather, they will be left separately with appropriate define statements for RequireJs. We are aware that it is possible, using the requirejs task for Grunt, to concatenate all these files into a single file, however this requires us to put import statements inside our internal project, where they would not be needed.

What we are looking for is a way to concatenate all the TypeScript files in a way that they bundle all the imports needed and that they include a single define block with all external dependencies to all the classes collected.

So far, we haven't found a Grunt task to optimize multiple define statements into a single define block. We can see two strategies:

  1. Concatenate all TypeScript files into a single file and compile it. Problem: How to deal with multiple import statements (e.g. in the example above, MyClass1 and MyClass2 both depend on jquery), which leads to TypeScript compilation errors.
  2. Compile each file individually and reduce ex post multiple define blocks into a single block.

Has anyone solved this problem? What are best practices for dealing with multiple files with external dependencies using Grunt / require? Are there any utilities that would allow us to refactor TypeScript to deal with multiple imports (analogous to Roslyn for C#)?

Upvotes: 2

Views: 874

Answers (2)

Lukasz Wojciak
Lukasz Wojciak

Reputation: 89

You shouldn't use --out as it tries to figure out the dependency order and will fill when you have external dependencies and AMD modules + it's slow and really unmaintainable in larger projects.

The best way to achieve a working build is to just compile to multiple .js files and then use a bundler as the next build step (rjs/systemjs/webpack) or browserify if you switch to commonJS modules.

Upvotes: 1

gilamran
gilamran

Reputation: 7294

You can use systemjs to load your modules in dev time, and systemjs builder to bundle all the needed file into one file.

Upvotes: 1

Related Questions