nx/packages/workspace/src/generators/utils/insert-statement.ts
Phillip Barta 52e3083a19
feat(core): added encoding param in Tree.read() (#5668)
feat(core): added encoding param in Tree.read()
2021-05-17 21:03:04 -04:00

36 lines
889 B
TypeScript

import { applyChangesToString, ChangeType, Tree } from '@nrwl/devkit';
import {
createSourceFile,
isImportDeclaration,
ScriptTarget,
} from 'typescript';
/**
* Insert a statement after the last import statement in a file
*/
export function insertStatement(tree: Tree, path: string, statement: string) {
const contents = tree.read(path, 'utf-8');
const sourceFile = createSourceFile(path, contents, ScriptTarget.ESNext);
const importStatements = sourceFile.statements.filter(isImportDeclaration);
const index =
importStatements.length > 0
? importStatements[importStatements.length - 1].getEnd()
: 0;
if (importStatements.length > 0) {
statement = `\n${statement}`;
}
const newContents = applyChangesToString(contents, [
{
type: ChangeType.Insert,
index,
text: statement,
},
]);
tree.write(path, newContents);
}