TSify ignores transforms during Browserify

716 Views Asked by At

In my gulp-based workflow, I am trying to apply a transform to all typescript files before tsify compiles it:

gulp.task(
  'deploy-typescript', 
  function() {
    var modulePath = configuration.files.typescript.entry;
    var bundleStream = browserify([modulePath])
      .transform(includeTemplates)
      .plugin(tsify)
      .bundle();

    return bundleStream
      .pipe(sourcestream(configuration.files.typescript.bundle))
      .pipe(gulp.dest(configuration.files.typescript.destination));
  }
);

var includeTemplates = function(file, options) {
  return through(function(buffer, encoding, next) {
    this.push('!test!');
    next();
  }
}

However, it appears that the tsify plugin ignores any changes my plugin makes to the source files and uses the .ts files as they exist on disk. The generated bundle does not include any of the changes I expect my transform to make.

1

There are 1 best solutions below

0
On

Unfortunately, what you have discovered is not a bug, but is the by-design behaviour.

tsify transforms TypeScript to JavaScript using TypeScript's Compiler API. Specifically, it implements the CompilerHost interface:

createProgram abstracts any interaction with the underlying system in the CompilerHost interface. The CompilerHost allows the compiler to read and write files, get the current directory, ensure that files and directories exist, and query some of the underlying system properties such as case sensitivity and new line characters.

The transformation is not performed file-by-file. Rather, the entire program is compiled and the resultant, transformed files are held in memory and are later passed to Browserify. This compilation involves the TypeScript compiler infrastructure reading the files from disk.

The author's comments are here:

How to transform typescript before tsify compiles it?

This is unfortunately impossible because of architectural limitations. tsify has to load files from disk because it pulls in extra files according to module resolution semantics. Even if it's possible to pass those extra files through the pre-tsify transformation pipeline (which I'm thinking is unlikely), it would be disastrously unperformant. You have to write your transformed files to disk before pulling them in to Browserify, sorry :/