Giter VIP home page Giter VIP logo

gulp-tsc's Introduction

gulp-tsc NPM version Build Status Dependency Status

TypeScript compiler for gulp 3

Usage

First, install gulp-tsc as a development dependency:

npm install --save-dev gulp-tsc

Then, add it to your gulpfile.js:

var typescript = require('gulp-tsc');

gulp.task('compile', function(){
  gulp.src(['src/**/*.ts'])
    .pipe(typescript())
    .pipe(gulp.dest('dest/'))
});

API

typescript(options)

options.tscPath

Type: String Default: null

The path to tsc command for compile.

If not set, this plugin searches for tsc command in the order as described below:

  1. from typescript module installed as your project's dependency (i.e. require("typescript") on current directory)
  2. from PATH of the running shell (using node-which)
  3. from Bundled typescript module

(This search list can be modified by options.tscSearch)

So, if you want to use other version of tsc command, you can add any version of typescript module to your project's dependecy.

However, this plugin could fail to run the future tsc because of incompatible changes of arguments.

options.tscSearch

Type: Array of String Default: ['cwd', 'shell', 'bundle']

This option changes how this plugin searches for tsc command on your system.

See options.tscPath for details.

options.emitError

Type: Boolean Default: true

If set to true, this plugin emits error event on compilation failure, which causes gulp to abort running task.

See Error handling for details.

options.module

Type: String ("commonjs" or "amd") Default: "commonjs"

--module option for tsc command.

options.target

Type: String ("ES3" or "ES5") Default: "ES3"

--target option for tsc command.

options.out

Type: String Default: null

--out option for tsc command.

options.outDir

Type: String Default: null

A path to the directory where output files are finally going to.

This option does not affect the actual output directory for tsc command.

See Path modification for usage of this option.

options.mapRoot

Type: String Default: null

--mapRoot option for tsc command.

options.sourceRoot

Type: String Default: null

--sourceRoot option for tsc command.

options.allowbool

Type: Boolean Default: false

--allowbool option for tsc command. (version 0.9.1.1)

options.allowimportmodule

Type: Boolean Default: false

--allowimportmodule option for tsc command. (version 0.9.1.1)

options.declaration

Type: Boolean Default: false

--declaration option for tsc command.

Generated .d.ts file is also piped into the stream.

Notice: If your output files are NOT going to {working directory}/something/ (to a directory beneath the working directory), you have to tell your output path to gulp-tsc by outDir option for correct reference paths. See Path modification for details.

options.noImplicitAny

Type: Boolean Default: false

--noImplicitAny option for tsc command.

options.noResolve

Type: Boolean Default: false

--noResolve option for tsc command.

options.removeComments

Type: Boolean Default: false

--removeComments option for tsc command.

options.sourcemap

Type: Boolean Default: false

--sourcemap option for tsc command.

Generated .js.map file is also piped into the stream.

Notice: If your output files are NOT going to {working directory}/something/ (to a directory beneath the working directory), you have to tell your output path to gulp-tsc by outDir option or sourceRoot option. See Path modification for details.

options.tmpDir

Type: String Default: '' (current working directory)

A path relative to current working directory, where a temporary build folder will be put in.

Notice: If you use this option with sourcemaps, consider to specify outDir or sourceRoot. See options.sourcemap for details.

If you are watching some files in current working directory with gulp.watch(), the creation of temporary build folder will trigger a folder change event.

If this is unexpected, you can put temp folders in a non-watched directory with this option.

Example:

gulp.task('tsc', function() {
  return gulp.src(src.ts)
        .pipe(tsc({tmpDir:'.tmp'}))
        .pipe(gulp.dest('.tmp/js'));
});

This will put a temporary folder in '.tmp'.

See Temporary directory and file by gulp-tsc for details.

options.noLib

Type: Boolean Default: false

--noLib option for tsc command.

Set noLib to true will dramatically reduce compile time, because 'tsc' will ignore builtin declarations like 'lib.d.ts'.

So if you are not using 'lib.d.ts' or prefer speed, set this to true. (In my case noLib:true only takes 25% time compared to noLib:false)

options.keepTree

Type: Boolean Default: true

If set to false, gulp-tsc skips creating a temporary file in your source directory which is used for keeping source directory structure in output.

See Temporary directory and file by gulp-tsc for details.

options.pathFilter

Type: Object, Function Default: null

This option is used for modifying paths of compiled files.

You can pass a Hash-like object which is a mapping of output paths in relative form.

Example:

gulp.task('compile', function(){
  gulp.src(['src/**/*.ts'])
    .pipe(typescript({
      pathFilter: { 'aaa/bbb': 'xxx/yyy' }
    }))
    .pipe(gulp.dest('build/'))
});

The example above will compile src/aaa/bbb/ccc.ts into build/xxx/yyy/ccc.js.

You can also pass a function which takes a relative path of compiled files as an argument and returns a modified path.

Example:

gulp.task('compile', function(){
  gulp.src(['src/**/*.ts'])
    .pipe(typescript({
      pathFilter: function (path) { return path.replace(/^aaa\/bbb/, 'xxx/yyy') }
    }))
    .pipe(gulp.dest('build/'))
});

A path filter function will receive following two arguments:

  • String: A relative path to a compiled file.
  • vinyl.File: A vinyl.File object of a compiled file.

A path filter function can return Boolean, String, vinyl.File or undefined.

Returned value Effect
true, undefined Use the file as-is.
false Skip the file. (not piped into output gulp stream)
String Replace the file's path with the returned string.
vinyl.File Use the returned vinyl.File instead.

options.safe

Type: Boolean Default: false

By default, gulp-tsc ignores warnings from tsc command and emits compiled js files to the gulp stream anyway.

If set this option to true, gulp-tsc never emits compiled files when tsc command returned warnings or errors.

Error handling

If gulp-tsc fails to compile files, it emits error event with gutil.PluginError as the manner of gulp plugins.

This causes gulp to stop running on TypeScript compile errors, which is sometimes a problem like using with gulp.watch().

If you want to suppress the error, just pass { emitError: false } to gulp-tsc like below.

var typescript = require('gulp-tsc');

gulp.task('default', function () {
    gulp.watch('src/**/*.ts', ['compile'])
});

gulp.task('compile', function () {
    return gulp.src('src/**/*.ts')
        .pipe(typescript({ emitError: false }))
        .pipe(gulp.dest('dest/'));
});

Path modification

gulp-tsc does some modification to output files to correct relative paths in sourcemap files (.js.map) and declaration files (.d.ts).

However, gulp-tsc doesn't know where your output files are going to be stored finally since it is specified by gulp.dest and gulp-tsc cannot access to it. So gulp-tsc assumes that your output files go into {working directory}/something/ by default.

If your output files are not going there, you have to tell your output path to gulp-tsc by outDir option.

If you have a gulp task like this:

gulp.task('compile', function(){
  gulp.src(['src/**/*.ts'])
    .pipe(typescript({ sourcemap: true, declaration: true }))
    .pipe(gulp.dest('foo/bar/'))
});

Output files are going under {working directory}/foo/bar/, but sourcemap files and declaration files will contain a relative path to source files from {working directory}/foo/ which is not correct.

To fix the relative path, just specify outDir same as your gulp.dest path.

gulp.task('compile', function(){
  gulp.src(['src/**/*.ts'])
    .pipe(typescript({ sourcemap: true, declaration: true, outDir: 'foo/bar/' }))
    .pipe(gulp.dest('foo/bar/'))
});

Temporary directory and file by gulp-tsc

Since gulp-tsc uses tsc command internally for compiling TypeScript files, compiled JavaScript files require to be written on the file system temporarily.

For those compiled files, gulp-tsc creates a temporary directory named gulp-tsc-tmp-* in the current working directory. You can change the location of the temporary directory by options.tmpDir.

In addition, gulp-tsc also creates a temporary file named .gulp-tsc-tmp-*.ts in your source root directory while compiling. The source root is determined by your gulp.src(). (e.g. For gulp.src("src/**/*.ts"), the source root is src/)

This is required for keeping your source directory structure in output since tsc command omits the common part of your output paths.

If you do not need to keep the structure, you can skip creating the temporary file by setting options.keepTree to false.

gulp-tsc's People

Contributors

ccll avatar kotas avatar youpy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-tsc's Issues

Use watch option for tsc

Hello,

I'm trying gulp-tsc and it seems when you're watching, it restarts the compiler every time a file changes (and it takes about 2-3s on my machine).

Is it possible to have an option to start the compiler with the -w option as it should be much faster.

I'll have a look at the code later this week but let me know what you think of it

Declaration files get the wrong reference

I have the following in my gulpfile.js:

gulp.task("typescript", function() {
     return gulp.src([
            "/**/*.ts",
        ], {base: "."})
        .pipe(gulpFilter("!**/*.d.ts"))
        .pipe(typescript({
            module: "commonjs",
            declaration: true,
            target: "es5",
        }))
        .pipe(gulp.dest("."))
});

This generates all .js and .js.map files correctly and the .d.ts files look fine too, except that any reference to a .d.ts file (e.g. /// <reference path="../typings/lib.d.ts"/>) will get mangled to one level too far back and becomes
/// <reference path="../../typings/lib.d.ts"/>, which is of course wrong, because the .d.ts files are written in the same directory as the .ts source files.

I did a bit of debugging here, and I think that the reason for this behavior is because the files are first generated to a temporary directory (gulp-tsc-tmp-*) and then copied back to their eventual destination. Because I used gulp.dest(".") I assumed that these references would stay intact, but apparently they do not.

allowBool does not work

Hi, using

tsc( {allowBool : true})

it will still say angular.d.ts(32,43): Cannot find name 'bool'.

besides, the gulp-tsc docu is wrong, it "Bool" is uppercase and should be enabled by default

There's no way to specify flags such as --emitDecoratorMetadata

I am using gulp-tsc to compile TypeScript files in an Angular 2 application. According to Angular's doc the files must be generated with the following line:

tsc --watch -m commonjs -t es5 --emitDecoratorMetadata file.ts

My gulpfile.js file is as follows:

gulp.task('compile-ts', function(){
  return gulp.src(['resources/angular/**/*.ts'])
    .pipe(typescript({target : "ES5", module : "commonjs" }))
    .pipe(gulp.dest('./public/angular/'))
    .pipe(plugins.livereload());
});

It supports specifying ES5 and commonjs but there's no way to add the flag --emitDecoratorMetadata

Prevent TypeScript beta version from getting installed

I just re-installed gulp-tsc and it brought typescript 1.1.0-1 with it - the newest beta version of the typescript compiler, which is still buggy and doesn't compile my code. Perhaps it is wise to adjust package.json so that only typescript 1.0.x versions will get installed?

Unhandled error when compilation failed

I use gulp-tsc with watch task.
If i have an error in my ts files and hit save, an unhandled error is thrown and gulp exits.

I believe this error should be caught so that i can fix my code without restarting gulp

In windows, error messages are displayed as "Buffer"

[11:11:30] [tsc] > <Buffer 6d 65 73 73 61 67 65 20 54 53 36 30 38 31 3a 20 41 72 67 75 6d 65 6e 74 20 66 6f 72 20 27 2d 2d 6a 73 78 27 20 6d 75 73 74 20 62 65 20 27 70 72 65 73 ... >

It looks like the lib "byline" is causing the issue but I'm not quite sure.
Changing lines 227 to 235 in compiler.js "fixes" the issue.

proc.on('error', function (err) {
    _this.emit('error', err);
  });
  stdout.on('data', function (chunk) {
    _this.emit('stdout', chunk.toString('utf8'));
  });
  stderr.on('data', function (chunk) {
    _this.emit('stderr', chunk.toString('utf8'));
  });

Node version is v6.2.2, gulp-tsc is 1.1.5 and tsc is 1.8.10.

Fails on .d.ts file

The plugin appears to throw an error when compiling a .d.ts file because there is no .js file output. It appears to be trying to open the file, but it does not exist.

I think it's common to put a single .d.ts file in the root of the application and reference it from the rest of the project.

Windows 7 error

Hello.

I am having strange error when trying to compile any .ts via gulp-tsc (tried both 0.0.2 and 0.0.3)
Here is the output:

[gulp] Failed to compile TypeScript: Error: Command failed:
module.js:340
    throw err;
          ^
Error: Cannot find module '...\Documents\frontend\tool\'C:\Program'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

Seems like the module path is screwed.
However, in Ubuntu it works.
Any idea for workaround?
Thanks.

Temp Folders are not cleaned up.

In my project I have multiple typescript file groups that need to be compiled separately (a library, and it's unit tests). I have tried adding them both to the same task, and separate tasks. They compile successfully, but the 2nd task leaves behind a temp folder in the project root containing the output file from the 2nd compilation.

Support direct command line params

It will be useful to support specifying tsc command line arguments directly, as simple string.
TSC is growing up, 1.4.1 is on air, and some new keys added - --suppressImplicitAnyIndexErrors --preserveConstEnums, etc...
In fact, we can tract each property of options object as tsc argument, and pass it directly (if option name is unknown), with conversion of boolean values, whereas string values passed as they are.

Compling error in Windows 8

Hi there,
I'm getting an error when I use your plugin in Windows 8. In Linux works fine though.

[gulp] Failed to compile TypeScript: Error: Command failed: The filename, directory name, or volume label syntax is incorrect

Incorrect reference path in generated definition file

Hello!

I successfully compiled my .ts script using command line:

tsc source/ts/docmaster/document/Explorer.class.ts --module commonjs --target ES5 --out source/ts/d.ts/docmaster/docmaster.js --declaration --noEmitOnError --removeComments

In compiled .d.ts file I see correctly used references.

/// <reference path="../DefinitelyTyped/jstorage/jstorage.d.ts" />
/// <reference path="../jquery/a2j.d.ts" />
/// <reference path="../DefinitelyTyped/q/Q.d.ts" />

I need to reproduce compiling in gulp script

gulp.task('test', function (callback) {
    gulp.src([
        'source/ts/docmaster/document/Explorer.class.ts'
    ])
        .pipe(tsc({
            module: 'commonjs',
            target: 'ES5',
            out: 'source/ts/d.ts/docmaster/docmaster.js',
            declaration: true,
            noEmitOnError: true,
            removeComments: true
        }))
        .pipe(gulp.dest(''))
        .pipe(notify('docmaster.js compiled'));
});

But in compiled d.ts my references are different:

/// <reference path="../../../../../source/ts/d.ts/DefinitelyTyped/jstorage/jstorage.d.ts" />
/// <reference path="../../../../../source/ts/d.ts/jquery/a2j.d.ts" />
/// <reference path="../../../../../source/ts/d.ts/DefinitelyTyped/q/Q.d.ts" />

Why?

[tsc] > The command line is too long. When compiling a lot of files

The TypeScript compiler can take in all command line arguments via a temporary file, as described here:
http://stackoverflow.com/questions/12699781/how-can-i-pass-multiple-source-files-to-the-typescript-compiler

We encountered this error months and months ago prior to using gulp, when Microsoft was forced to do the same thing (pass all the source file names and arguments in via file). Could you make this change to
/lib/compiler.js to support this argument file? I will be working on a pull request myself

Feature request: search for typescript compiler in parent directories

The feature where gulp-tsc will use the typescript compiler in node_modules is helpful in the case that different projects are using different versions of typescript (I'm in this situation).

In my case, it would also be helpful if instead of just searching for typescript in the ./node_modules it would also search in ../node_modules, ../../node_modules, etc.

What do you think?

Thanks,

Chris

Double backslashes on Windows

gulp-tsc uses a 'shellescape' function that processes the arguments passed to tsc. This function replaces backslashes by double backslashes. This results in invalid paths on Windows. Some Windows versions don't care (e.g. Windows 7) but others do (e.g. Windows 8, Windows Server 2008). I have several computers where gulp-tsc does not work for this reason.

Would it be possible to disable backslash escaping on Windows?

Duplicate output directory when input file refers to files outside (v0.5.1)

Reported by @bestander in #18 (comment)


Hi, thanks for the best gulp tsc task.
I think this pull request broke my build and I reverted to version 0.5.0.

This is my setup:

gulp.task('compile-typescript', function() {
    return gulp.src(['app/**/*.ts'])
        .pipe(cache('typescript'))
        .pipe(typescript(typescriptOptions))
        .pipe(gulp.dest(webOutputPath + '/app'));
});
gulp.task('dev', function(callback) {
    runSequence('clean-web-output',
        ['compile-typescript', 'compile-sass' ],//, 'run-tests'],
        function() {
            gulp.watch(['app/**/*.ts'], ['compile-typescript']);
        });
});

If I change one TS file I expect 1 or more JS files to be compiled into my .tmp folder.

For example if I change:

/app/online-reader/popup-reader-directive.ts

Then compiler produces this list:

<tmp>/online-reader/popup-reader-directive.js
<tmp>/online-reader/reader-preferences-service.js
<tmp>/analytics/http-latency-sampler.js

The change in this ticket changes it to:

<tmp>/online-reader/online-reader/popup-reader-directive.js
<tmp>/online-reader/online-reader/reader-preferences-service.js
<tmp>/online-reader/analytics/http-latency-sampler.js

Which os wrong.

I am happy to debug or provide more test data.

Under 0.5.0, output files are missing

I upgraded to 0.5.0 from 0.0.4, and I don't see any .js files after doing a build.

Here is my gulp task:

gulp.task('typescript', ['clean'], function() {
    var typescript = require('gulp-tsc');

    return gulp.src(['./**/*.ts', '!./node_modules/**'], { read: false })
      .pipe(typescript({ noImplicitAny: true, target: 'ES5', module: 'COMMONJS', sourcemap: true }))
      .pipe(gulp.dest('.'));
  });

 gulp.task('build', ['clean', 'typescript'], function(){

  });

Here is a screencast which attempts to demonstrate that I am not crazy:

http://screencast.com/t/JX1y89rA

Cross-project dependencies

I have two typescript projects (app and util). The app project references files in the util project.

I set up my gulp-tsc with sources from the app project, but during compilation, the typescript compiler also compiles files in the util project. This is mostly ok, but because the util files don't get added to the gulp output files, there's a couple caveats:

  • The files under util don't get moved to the destination. This is actually a good thing because I wouldn't want them moved under app.
  • Further "pipes" in the gulp stream don't get applied to the util files.

I'm not even sure there's anything worthwhile to do about this, but just thought I'd bring it up to see if you had any ideas.

Thanks,

Chris

References are messed up on (d.ts)

While compiling typescript using gulp-tsc , I seem to encounter a strange issue. The file references on the d.ts seems to be messed up.

Source :

///<reference path='typings/lodash/lodash.d.ts'/>
///<reference path='typings/angularjs/angular.d.ts'/>

Gulp

    return gulp.src('src/gravy/gravy.ts')
        .pipe(tsc({sourcemap: true,declaration:true,logErrors: true, out:'gravy.js',outDir:'src/gravy'}))
        .pipe(gulp.dest('src/gravy'));

Generated d.ts file.

/// <reference path="typings/lodash/lodash.d.ts" />
/// <reference path="../src//gravy/typings/angularjs/angular.d.ts" />

See the generated file , the references are messed up. Its strange that the first line is good , the second line always seems to be messed. I reversed the order on the source to see same symptom.
The generated mapping file out of equivalent typescript CLI is good. Any ideas ?

Thanks
Santhosh

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.