TypeScript:编译删除未引用的导入 [英] TypeScript: compiling removes unreferenced imports

查看:157
本文介绍了TypeScript:编译删除未引用的导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例:

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();
});

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

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();

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

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

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

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

推荐答案

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

A nicer solution (tested with TS 1.8):

import 'just/referencingthis/forpackaging';

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

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.

这篇关于TypeScript:编译删除未引用的导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆