Skip to content

Instantly share code, notes, and snippets.

@AttilaGal
Last active December 11, 2016 15:20
Show Gist options
  • Save AttilaGal/f8e7e221b7537a105d16f52c97eec144 to your computer and use it in GitHub Desktop.
Save AttilaGal/f8e7e221b7537a105d16f52c97eec144 to your computer and use it in GitHub Desktop.
adds and ES2015 import statement for angular in any js/ts file within a directory
/*
This is a helper script that can be used to recursively insert an
angular import statement into all .ts files in a given directory.
call:
node renamer <directory>
*/
var fs = require('fs');
var path = require('path');
var linesert = require( "linesert" );
var ANSI_GREEN = '\x1b[32m';
var ANSI_DEFAULT = '\x1b[0m';
var ANSI_RED = '\x1b[35m';
var importStatement = "import * as angular from 'angular';";
var walkSync = function(dir, filelist) {
var files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
filelist = walkSync(path.join(dir, file), filelist);
}
else {
if(getFileExtension(file) === 'ts'){
insertAngularStatement(path.join(dir, file));
}
}
});
return filelist;
};
var getFileExtension = function(file){
var splitted = file.split('.');
return splitted[splitted.length - 1];
};
var insertAngularStatement = function(pathToFile){
linesert(pathToFile).beforeLine(1).insert(importStatement, function(err, result){
if(err){
console.log(ANSI_RED, 'error while inserting into ' + pathToFile, ANSI_DEFAULT);
}else{
console.log(ANSI_GREEN,'successfully inserted angular into ' + pathToFile + ANSI_DEFAULT );
}
});
}
walkSync(process.argv[2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment