在打字稿中使用外部类,避免使用引用

时间:2016-10-13 06:37:16

标签: typescript typescript-typings

我正在使用rusha进行sha1散列和gulp-typescript来编译打字稿。

rusha没有dt所以我创建了一个定义并将其存储在$("#myinput1").on('blur', function() .... ); 下:

typings/custom/rusha.d.ts

并通过declare class Rusha { digest(data: any): string; digestFromString(strityng: string): string; } 安装。

这是我typings install file:typings/custom/rusha.d.ts --global的相关部分:

gulpfile.js

这是我的var gulp = require('gulp'); var gulpTS = require('gulp-typescript'); var gulpSourcemaps = require('gulp-sourcemaps'); var tsConfig = require('./tsconfig.json'); gulp.task('script', function() { return gulp.src('./src/script/**/*.ts') .pipe(gulpSourcemaps.init()) .pipe(gulpTS(tsConfig.compilerOptions)) .pipe(gulpSourcemaps.write()) .pipe(gulp.dest('./public/script')); });

tsconfig.json

现在我在文件{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false } } 中创建了一个类User,其中包含以下内容:

src/script/User.ts

问题:

export class User {
    public username: string;
    public firstName: string;
    public lastName: string;
    public email: string;

    private sha1Password: string;
    private rusha: Rusha = new Rusha();

    set password(value: string) {
        this.sha1Password = this.rusha.digest(value);
    }

    public checkPassword(password: string) {
        return this.sha1Password === this.rusha.digest(password);
    }

    public setSha1Password(sha1Password: string) {
        this.sha1Password = sha1Password;
    }
}

当我添加$ npm run gulp script > xxx@xxx gulp /home/xxx/path/to/xxx > gulp "script" [08:29:25] Using gulpfile ~/path/to/xxx/gulpfile.js [08:29:25] Starting 'script'... src/script/User.ts(9,20): error TS2304: Cannot find name 'Rusha'. src/script/User.ts(9,32): error TS2304: Cannot find name 'Rusha'. [08:29:27] TypeScript: 2 semantic errors [08:29:27] TypeScript: emit succeeded (with errors) [08:29:27] Finished 'script' after 1.66 s 时,它与///<reference path="../../typings/custom/rusha.d.ts"/>一样有效。但是当我添加///<reference path="../../typings/globals/rusha/index.d.ts"/>时,它会抛出许多重复的声明,等等。

似乎这个文件没有加载但是其他文件被加载了(例如从core-js中设置)。但不仅///<reference path="../../typings/index.d.ts"/>看起来正确。 index.d.ts看起来也是正确的:

typings.json

1 个答案:

答案 0 :(得分:0)

gulp-tsc也有类似的问题。到目前为止,我找到的唯一解决方案是将自定义ts定义添加到gulp任务中:

var gulp = require('gulp');
var gulpTS = require('gulp-typescript');
var gulpSourcemaps = require('gulp-sourcemaps');
var tsConfig = require('./tsconfig.json');

gulp.task('script', function() {
  return gulp.src([
    './typings/index.d.ts',
    './src/script/**/*.ts'
  ])
      .pipe(gulpSourcemaps.init())
        .pipe(gulpTS(tsConfig.compilerOptions))
      .pipe(gulpSourcemaps.write())
      .pipe(gulp.dest('./public/script'));
});