37

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?

thomaux
  • 19,133
  • 10
  • 76
  • 103
  • I'm assuming you couldn't just move the import to the appropriate module? – Fenton Mar 07 '13 at 13:29
  • 2
    They are in the appropriate module. My project consists mainly out of widgets. Each widget is packed in its own module. I'm using Handlebars for templating and want to pack the resulting views together with my widget definition files. When referencing such a view, it will expose a method with the same name on the global variable 'Handlebars'. Hence I don't need to reference the module as it will have defined the method for me. – thomaux Mar 07 '13 at 13:54

2 Answers2

26

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

/// <amd-dependency path="just/referencingthis/forpackaging" />
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
11

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.

bcody
  • 2,489
  • 1
  • 21
  • 21