gulp-traceur-compiler
Version:
Compiles ES6 to ES3/ES5 using the Traceur Compiler
129 lines (91 loc) • 3.17 kB
JavaScript
;
var pluginName = 'gulp-traceur-compiler',
gutil = require('gulp-util'),
through2 = require('through2'),
PluginError = gutil.PluginError,
assign = require('object-assign'),
traceur = require('traceur'),
recursiveCompiler = require('./lib/recursiveModuleCompile'),
generateMaps = require('vinyl-sourcemaps-apply'),
path = require('path'),
cwd = process.cwd();
module.exports = function (options, singleFile) {
var compiler;
// check for string too for
// backward compatibility
// will be ignored but trigger single file.
if('boolean' === typeof options || 'string' === typeof options){
singleFile = options;
options = undefined;
}
options = assign({modules: 'commonjs'}, options);
// inline requires single file output.
if(options.modules === 'inline')
singleFile = true;
// prevent turning on sourcemaps
if(options.sourceMaps){
options.sourceMaps = false;
gutil.log(pluginName, 'Please npm install "gulp-sourcemaps". Traceur sourcemaps disabled. See README.md.');
}
// turn on module name if prefix is used.
if(options.prefix && !options.moduleName){
options.moduleName = true;
options.prefix = options.prefix.replace(/\\/g, '/');
options.prefix = options.prefix.replace(/\/$/, '') + '/';
}
if(options.out){
singleFile = true;
options.out = undefined;
}
compiler = new traceur.NodeCompiler(options);
function checkSourceMaps(file) {
var sourceMap = file.sourceMap && compiler.getSourceMap();
if (sourceMap) {
generateMaps(file, sourceMap);
}
}
return through2.obj(function (file, enc, cb) {
var self = this;
if (file.isNull())
return cb(null, file);
if (file.isStream()) {
self.emit(new PluginError(pluginName,'Streaming not supported.'));
cb();
}
var compiled;
if(singleFile){
var rootSources = [{name: file.path, type: 'module', format: options.modules }];
// get recursiveCompiler methods
// pass traceur and instantiated compiler.
var _recursiveCompiler = recursiveCompiler(traceur, compiler);
_recursiveCompiler.recursiveModuleCompileToSingleFile(rootSources, options, file.path,
function (err, compiled) {
if(err){
if(err instanceof Array)
err = err.join('\n');
self.emit('error', new PluginError(pluginName, err || err.message || 'Unknown exception ocurred.'));
}
if(compiled){
file.contents = new Buffer(compiled);
checkSourceMaps(file);
self.push(file);
}
process.chdir(cwd);
cb();
});
} else {
// contents, sourceName, outputName, sourceRoot
var sourceName = options.prefix ? options.prefix + file.relative : file.relative;
compiled = compiler.compile(file.contents.toString(), sourceName, file.relative, file.base);
if(!compiled){
this.emit('error', new PluginError(pluginName, 'The file ' + file.relative + ' failed to compile.'));
cb();
}
file.contents = new Buffer(compiled);
checkSourceMaps(file);
this.push(file);
cb();
}
});
};
module.exports.RUNTIME_PATH = traceur.RUNTIME_PATH;