Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: compiling removes unreferenced imports

In our project we're using RequireJS as our module loader. Some of our modules will influence global libraries, and hence won't be directly used within the module they are referenced in.

Example:

define(['definitely/goingto/usethis/','just/referencingthis/forpackaging'], function(useThis) {
    useThis.likeIPromised();

    // the following call can only be made when the second required file is available
    someGlobalAvailableVariable.someMethod();
});

This works as expected when writing my modules in JavaScript. However, we're translating our project step by step to TypeScript. Given the example above, this results in:

import useThis = module("definitely/goingto/usethis/");
import whatever = module("just/referencingthis/forpackaging");

useThis.likeIPromised();

// I've written a definition file so the following statement will evaluate
someGlobalAvailableVariable.someMethod();

And when compiling this to JavaScript, the compiler wants to be helpful and removes any unused imports. As such, this breaks my code, cause the second imported module isn't available.

My current work around is to include a redundant assignment, but this looks ugly:

import whatever = module("just/referencingthis/forpackaging");
var a = whatever; // a is never ever used further down this module

Does anyone know if it's possible to configure the TypeScript compiler to not optimize modules during compile?

like image 559
thomaux Avatar asked Mar 07 '13 09:03

thomaux


2 Answers

You can do this at the top of your file (instead of import):

/// <amd-dependency path="just/referencingthis/forpackaging" />
like image 111
Ryan Cavanaugh Avatar answered Oct 20 '22 19:10

Ryan Cavanaugh


A nicer solution (tested with TS 1.8):

import 'just/referencingthis/forpackaging';

The amd-dependency triple-slash-directive seems to only work if there are other require imports; only having amd-dependency directives results in the TypeScript compiler generating JavaScript completely without a module definition.

like image 20
bcody Avatar answered Oct 20 '22 19:10

bcody