Skip to content

Instantly share code, notes, and snippets.

@GabiGrin
Created July 27, 2015 12:00
Show Gist options
  • Select an option

  • Save GabiGrin/7a36193d71e6d28d9cd5 to your computer and use it in GitHub Desktop.

Select an option

Save GabiGrin/7a36193d71e6d28d9cd5 to your computer and use it in GitHub Desktop.
migrate typescript using commonjs module syntax to es6 modules sytax
//run "npm install glob chalk" before running this
'use strict';
/*global console*/
var glob = require('glob');
var fs = require('fs');
var chalk = require('chalk');
var pattern = '{src,e2e}/**/*.ts';
// var pattern = 'src/reply.i.ts';
var exportPattern = /(interface|function|enum|class) (.*) \{((\n|.)*)export = \2;/;
var importPattern = /import (.*) = require\((.*)\)/;
var exportCount = 0,
importCount = 0;
glob(pattern, function (err, files) {
console.log(chalk.blue('Found ', files.length, 'matching pattern'));
files.forEach(function (fileName) {
console.log(chalk.magenta('Going to read', fileName));
var fileContent = fs.readFileSync(fileName, 'utf8');
fileContent = fileContent.replace(exportPattern, function (string, type, name, content) {
console.log(chalk.blue(' replacing export pattern'));
exportCount++;
//https://github.com/Microsoft/TypeScript/issues/3194
if (type === 'interface') {
return type + ' ' + name + ' {' + content + '\nexport default ' + name;
}
return 'export default ' + type + ' ' + name + ' {' + content;
})
.replace(importPattern, function (string, importName, importPlace) {
console.log(chalk.blue(' replacing import pattern'));
importCount++;
return 'import ' + importName + ' from ' + importPlace;
})
.replace(/(\n)*$/, '\n'); //replace empty lines generated by the changes
fs.writeFileSync(fileName, fileContent, 'utf8');
console.log(chalk.green('Sucessfully migrated file [' + fileName + ']'));
});
console.log(chalk.green('#################\nSuccessfully migrated', chalk.white(exportCount), ' export clauses, and', chalk.white(importCount), 'clauses from ', chalk.white(files.length), 'files!'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment