3

当它编译我的代码时,TypeScript 在每个文件的顶部包含一个 __extends 声明:

var __extends = this.__extends || function (d, b) {
    /* istanbul ignore next */
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

这在幕后工作得很好,但是在使用 karma-coverage 之类的东西来生成报告时会产生不一致。该声明包含两个函数调用和代码中的一个分支(|| 用法),它们只会在第一个声明中执行,留下数十个(如果不是数百个)后续声明没有覆盖。这使得具有 100% 代码覆盖率的文件在覆盖率报告中看起来很糟糕。

有没有人解决过这个问题?

4

5 回答 5

4

我在 typescript codeplex 找到了一个工作项。我希望打字稿人尽快解决这个问题。您可以在此处找到更多信息:typescript workitem 2002

于 2014-04-07T18:37:03.963 回答
3

我刚刚在我的脚本任务中创建了一个函数,它将一个标题附加到任何使用继承的文件的顶部。这大大提高了代码覆盖率。我正在使用伊斯坦布尔,所以我的函数如下所示:

function istanbulIgnoreTypeScriptExtend() {
    var tsExtends = /^var __extends =/;
    return through.obj(function(file, enc, done) {
        if (file.isBuffer() && tsExtends.test(file.contents)) {
            file.contents = Buffer.concat([
                new Buffer('/* istanbul ignore next: TypeScript extend */' + os.EOL),
                file.contents
            ]);
        }
        this.push(file);
        done();
    });
}

我实际上可以将它作为一个 gulp 插件发布,但我希望很快有新的方法来解决这个问题。

于 2014-10-12T04:51:20.133 回答
1

这是使用他们的答案中提供的函数@jedmao和 gulp任务的示例。我已经稍微修改了它以处理不是文件中的第一件事(例如,如果你有一个或一个标签)。您可能还应该像 jedmao 那样使用,而不是像我在这里那样使用。var __extends='use strict'/// <referencesos.EOL\n

var gulp     = require('gulp');
var through2 = require('through2');

gulp.task('my-gulp-task', function() {
    gulp.src('*.ts')
        .pipe(myTypeScriptCompiler())
        .pipe(istanbulIgnoreTypeScriptExtend())
        .pipe(gulp.dest('myDestFolder'));
});

function istanbulIgnoreTypeScriptExtend() {
    var tsExtends = /var __extends =/;
    return through2.obj(function(file, enc, done) {
        if (file.isBuffer() && tsExtends.test(file.contents)) {
            var rows = file.contents.toString().split('\n');
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].indexOf('var __extends =') === 0) {
                    rows.splice(i, 0, '/* istanbul ignore next: TypeScript extend */');
                    break;
                }
            }
            file.contents = new Buffer(rows.join('\n'));
        }
        this.push(file);
        done();
    });
}
于 2015-06-16T01:57:44.380 回答
1

从 2.1 开始,typescript 支持外部帮助库,所有发出的函数都放在tslib包中

npm install --save tslib

更改您的 tsconfig:

{
    "compilerOptions": {
        //all the other stuff
        "importHelpers": true
    }
}

tslib然后 TypeScript 将在必要时自动导入包,如下例所示

var tslib_1 = require("tslib");

var MyClass = (function (_super) {
    tslib_1.__extends(MyClass, _super);
    function MyClass() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MyClass;
}(controller_1.Controller));
于 2017-04-15T11:57:28.183 回答
-2

extends打字稿编译器将在每个具有关键字的文件之上生成它。使其成为单一用途的唯一方法是编译为带有--out编译器标志的单个 js 文件。

于 2014-03-03T19:43:37.387 回答