Skip to content

Instantly share code, notes, and snippets.

@waldekmastykarz
Created September 2, 2020 17:43
Show Gist options
  • Save waldekmastykarz/4909355fc59251954c87943e28ccf831 to your computer and use it in GitHub Desktop.
Save waldekmastykarz/4909355fc59251954c87943e28ccf831 to your computer and use it in GitHub Desktop.
Remove method from a class in a .ts file
const ts = require('typescript');
const path = require('path');
const fs = require('fs');
function getAsEnumerable(file, node) {
const nodes = [node];
node.getChildren(file).forEach(n => {
nodes.push(...getAsEnumerable(file, n));
});
return nodes;
}
function readdirR(dir) {
return fs.statSync(dir).isDirectory()
? Array.prototype.concat(...fs.readdirSync(dir).map(f => readdirR(path.join(dir, f))))
: dir;
};
// remove method from a class command
const cmdPath = 'src/path';
const files = readdirR(cmdPath);
files.forEach(file => {
if (!file.endsWith('.ts') || file.endsWith('.spec.ts')) {
return;
}
const tsFile = ts.createSourceFile(path.basename(file), fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest);
const nodes = getAsEnumerable(tsFile, tsFile);
for (var i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node.name &&
node.name.text === 'commandHelp') {
fs.writeFileSync(file, tsFile.text.substr(0, node.pos) + tsFile.text.substr(node.end), 'utf8');
break;
}
}
});
{
"name": "removeTsMethod",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"typescript": "^3.9.7"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment