如何在 gulp 构建链中使用 ts-nameof,得到:未知的编译器选项 'getCustomTransformers'。?

How to use ts-nameof in the gulp build chain, getting: Unknown compiler option 'getCustomTransformers'.?

我在我的 TypeScript 文件中使用 ts-nameof 就像在这个 .ts-file:

import 'ts-nameof';

export class MyTsNameOfTest {
  public testTsNameOf() {
    const nameString = nameof(console.log);
  }
}

我的 Gulp 构建任务 - 按照此处的建议 Gulp configuration:

const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsNameof = require("ts-nameof");

gulp.task("typescript", function () {
  gulp.src("src/**/*.ts")
    .pipe(ts({
      getCustomTransformers: () => ({ before: [tsNameof] })
    }))
    .pipe(gulp.dest("./dist"));
});

运行 gulp 我得到错误:

error TS5023: Unknown compiler option 'getCustomTransformers'.

我使用的版本:

gulp 3.9.1
gulp-typescript 3.2.4
typescript 2.9.2
ts-nameof 2.0.0

我做错了什么?感谢您的帮助。

准备

安装所需的 npm

npm install typescript
npm install gulp@^4.0.0                
npm install gulp-typescript@^5.0.0
npm install del
npm install ts-nameof

gulp-typescript 没有项目

准备gulpfile.js

const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsNameof = require("ts-nameof");
const del = require('del');

gulp.task('clean', () => {
    return del(['./dist/**']);
});    

gulp.task('ts', function () {
    return gulp.src('./src/**/*.ts')
        .pipe(ts({
            getCustomTransformers: () => ({ before: [tsNameof] })
        }))
        .pipe(gulp.dest('./dist'));
});

gulp.task('default',
    gulp.series(
        'clean',
        'ts',
    ));

gulp-typescript 使用现有 tsconfig.json

的项目

gulp-typescript 与现有的 tsconfig.json 结合使用,必须在配置选项 getCustomTransformers 的地方调整 gulpfile.js

准备gulpfile.js

const gulp = require('gulp');
const ts = require('gulp-typescript');
const tsNameof = require("ts-nameof");
const del = require('del');

gulp.task('clean', () => {
    return del(['./dist/**']);
}); 

var tsProject = tsProject || null;
gulp.task('ts::Project', function () {
    if (!tsProject) {
        tsProject = ts.createProject(
            'tsconfig.json',
            {
                getCustomTransformers: () => ({ before: [tsNameof] })
            }
        );
    }
    return gulp.src('./src/**/*.ts')
        .pipe(tsProject())
        .pipe(gulp.dest("./dist"));
});

gulp.task('tsProject',
    gulp.series(
        'clean',
        'ts::Project',
    ));

转译

运行 gulpfile.js

./node_modules/.bin/gulp

./node_modules/.bin/gulp tsProject

执行

执行转译后的文件tsNameofTest.js

node dist/tsNameofTest.js  // expected output: nameString: log

备注: if typescript target is ESNext 我在 .ts 文件中的以下语句出现执行错误,因为它在最终文件中.js 文件也是:

import 'ts-nameof';

我得到的是用

替换它来修复
/// <reference path="../node_modules/ts-nameof/ts-nameof.d.ts" />

更新

现在甚至可以全局安装 ts-nameof 的类型定义:

npm install @types/ts-nameof --save-dev

import/// <reference path="" /> 都不需要。