【问题标题】:Why is typescript compiler omitting 'should.js' import in generated javascript?为什么打字稿编译器在生成的 javascript 中省略了“should.js”导入?
【发布时间】:2014-10-23 03:57:01
【问题描述】:

我遇到了一个奇怪的问题。在我的(比如说)a.ts 我有 -

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />

import should = require('should');

import something_else = require('../something-else');

现在当我使用命令编译时 -

tsc -m commonjs --outDir "./build" "src/test/a.ts"

我生成的 javascript 没有 require for should -

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />
var service_manager = require('../routes/service-manager');

这似乎是打字稿编译器中的一个错误,但我可能做错了。或者如果有一些解决方法,请分享。

【问题讨论】:

    标签: javascript node.js typescript mocha.js should.js


    【解决方案1】:

    这样做是因为您没有使用它。只要您实际使用 should 变量,它就会立即生效。例如

    /// <reference path="../typings/mocha/mocha.d.ts" />
    /// <reference path="../typings/should/should.d.ts" />
    
    import should = require('should');
    var persist = should; 
    

    原因:它允许您自己使用类型信息,而不需要对require('should') 产生运行时依赖。它还允许您在 AMD 场景中进行延迟加载。

    【讨论】:

    • 但我在 mocha 测试中使用它。喜欢 - res.body.should.equal('');
    • 只需使用var persist 技巧,我已经更新了答案
    • 这是一个 hack,但它有效!更重要的是感谢原因。
    • 如果你省略了“import should ="并且只有“require('should');”,这也可以工作
    • @John 如果你没有使用 import 并且 raw 需要你需要 raw 需要 lib 例如node.d.ts
    【解决方案2】:

    正如Eric Nicholson 的评论,只有require 没有import

    require('should');
    // use should
    

    另外,reference path 会默认捆绑在typings/tsd.d.ts,无需单独写入。

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 2020-03-07
      • 1970-01-01
      • 2021-11-30
      • 2022-11-22
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      相关资源
      最近更新 更多