TypeScript:编译删除未引用的导入

tho*_*aux 34 javascript amd requirejs typescript tsc

在我们的项目中,我们使用RequireJS作为模块加载器.我们的一些模块会影响全局库,因此不会直接在它们被引用的模块中使用.

例:

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();
});
Run Code Online (Sandbox Code Playgroud)

在JavaScript中编写模块时,这可以正常工作.但是,我们正在逐步将项目翻译为TypeScript.鉴于上面的示例,这会导致:

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();
Run Code Online (Sandbox Code Playgroud)

在将其编译为JavaScript时,编译器希望对您有所帮助,并删除任何未使用的导入.因此,这会破坏我的代码,导致第二个导入的模块不可用.

我目前的工作是包括一个冗余的任务,但这看起来很难看:

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

有谁知道是否有可能将TypeScript编译器配置为在编译期间不优化模块?

Rya*_*ugh 26

您可以在文件顶部执行此操作(而不是import):

/// <amd-dependency path="just/referencingthis/forpackaging" />
Run Code Online (Sandbox Code Playgroud)

  • 如果我使用commonjs该怎么办?我希望有一个命令行标志来关闭它:-( (7认同)
  • 如果使用commonjs或systemjs,这个答案似乎不起作用 (2认同)

bco*_*ody 8

更好的解决方案(使用TS 1.8测试):

import 'just/referencingthis/forpackaging';
Run Code Online (Sandbox Code Playgroud)

amd-dependency triple-slash-directive似乎只有在有其他需要导入的情况下才有效.只有amd-dependency指令才会导致TypeScript编译器在没有模块定义的情况下完全生成JavaScript.