Skip to content

Instantly share code, notes, and snippets.

@JLHwung
Last active June 22, 2017 08:44
Show Gist options
  • Select an option

  • Save JLHwung/c6d23b79bb404ede444f7afee0d7313f to your computer and use it in GitHub Desktop.

Select an option

Save JLHwung/c6d23b79bb404ede444f7afee0d7313f to your computer and use it in GitHub Desktop.
node walk-and-transform.js ./src/client/scripts
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const walk = require('fs-walk');
function transform(fileContent) {
const result = fileContent;
if (!fileContent.includes('angular.module')) {
return result;
}
let lines = result.split('\n');
let lastImportLines;
lines.forEach((line, index) => {
if (line.startsWith('import ') && !line.startsWith('import {')) {
lastImportLines = index;
return true;
}
});
let importLines = lines.splice(0, lastImportLines + 1);
if (lines[0] !== '') {
importLines.push('');
}
// let moduleNameLine;
// let exportLine;
// importLines.forEach((line, index) => {
// if (line.startsWith('const MODULE_NAME')) {
// moduleNameLine = index;
// }
// });
//
// if (moduleNameLine !== undefined) {
// importLines.push(importLines[moduleNameLine]);
// importLines.splice(moduleNameLine, 1);
// }
//
// importLines.forEach((line, index) => {
// if (line.startsWith('export default')) {
// exportLine = index;
// }
// });
//
// if (exportLine !== undefined) {
// importLines.push(importLines[exportLine]);
// importLines.splice(exportLine, 1);
// }
return [...importLines, ...lines].join('\n');
}
const folder = process.argv[process.argv.length - 1];
walk.files(path.resolve(process.cwd(), folder), (basedir, filename, stat, next) => {
if (filename.endsWith('.js') && basedir.indexOf('vendors') === -1) {
fs.readFile(path.join(basedir, filename), (err, data) => {
if (err) throw err;
const result = transform(data.toString());
console.log(chalk.green('writing results to'), path.join(basedir, filename));
fs.writeFile(path.join(basedir, filename), result, next);
});
} else {
next();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment