Angular 2 Ahead-of-Time Compiler with gulp-typescript

余生长醉 提交于 2019-12-02 19:38:02

I imagine the reason why the typescript: require(..) is not working is because gulp-typescript looks for something called typescript or tries to run the command tsc, and since the angular compiler command is ngc, it doesn't find it.

For now, if your project is just as simple as compiling it, you can just run the command from gulp like so:

var exec = require('child_process').exec;

gulp.task('task', function (cb) {
  exec('ngc -p "<path to your tsconfig.json>"', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
});

This requires that you have your tsconfig.json set up correctly, with the potential extra options that Google talk about here, under the Configuration heading.

If you need the more complex functionality that the gulp-typescript package provides, I'm afraid you're either going to have to develop it yourself, or wait for someone else to.

Bastiaan van den Berg

I was trying to get this to work as well and William Gilmour's answer helped a lot.

I extended it a little to run a local ngc installation (like the angular 2 example that runs the one in node_modules/.bin), and which works both on Linux and Windows systems:

var exec = require('child_process').exec;
var os = require('os');

gulp.task('build-ts', function (cb) {

    var cmd = os.platform() === 'win32' ? 
        'node_modules\\.bin\\ngc' : './node_modules/.bin/ngc';

    exec(cmd, function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

This is the cross-platform version of the gulpfile, which I am currently using for Ahead-Of-Time (AOT) compilation with angular 2:

//jshint node:true
//jshint esversion: 6
'use strict';

...

// helper function for running ngc and tree shaking tasks
const run_proc = (cmd, callBack, options) => {
        process.stdout.write(stdout);
        process.stdout.write(stderr);
        callBack(err);
    });
};


gulp.task('ngc', ['css', 'html', 'ts'], cb => {
    let cmd  = 'node_modules/.bin/ngc -p tsconfig-aot.json';
    if (isWin) {
        cmd  = '"node_modules/.bin/ngc" -p tsconfig-aot.json';
    }
    return run_proc(cmd, cb);
});

Feel free to check out the entire example of the Tour of Heroes (ToH) example with gulp.js on my github repo: ng2-heroes-gulp

This is for sure the short term solution, the long term solution for me will be the gulp-ngc plugin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!