TypeScript: compiling removes unreferenced imports

2019-02-02 20:39发布

问题:

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?

回答1:

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.



回答2:

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

/// <amd-dependency path="just/referencingthis/forpackaging" />