From 1057b665ac7c4a421402e2833740d553b9455fb6 Mon Sep 17 00:00:00 2001 From: Kononnable Date: Thu, 7 Nov 2019 22:03:01 +0100 Subject: [PATCH] remove unused import declarations --- src/ModelGeneration.ts | 19 ++++++++++++++++++- src/templates/entity.mst | 1 - 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/ModelGeneration.ts b/src/ModelGeneration.ts index 743dd74..226b1c7 100644 --- a/src/ModelGeneration.ts +++ b/src/ModelGeneration.ts @@ -55,13 +55,30 @@ export default function modelGenerationPhase( `${casedFileName}.ts` ); const rendered = compliedTemplate(element); - const formatted = Prettier.format(rendered, { parser: "typescript" }); + const withImportStatements = removeUnusedImports(rendered); + const formatted = Prettier.format(withImportStatements, { + parser: "typescript" + }); fs.writeFileSync(resultFilePath, formatted, { encoding: "UTF-8", flag: "w" }); }); } +function removeUnusedImports(rendered: string) { + const openBracketIndex = rendered.indexOf("{") + 1; + const closeBracketIndex = rendered.indexOf("}"); + const imports = rendered + .substring(openBracketIndex, closeBracketIndex) + .split(","); + const restOfEntityDefinition = rendered.substring(closeBracketIndex); + const distinctImports = imports.filter( + v => restOfEntityDefinition.indexOf(v) !== -1 + ); + return `${rendered.substring(0, openBracketIndex)}${distinctImports.join( + "," + )}${restOfEntityDefinition}`; +} function createHandlebarsHelpers(generationOptions: IGenerationOptions): void { Handlebars.registerHelper("json", context => { diff --git a/src/templates/entity.mst b/src/templates/entity.mst index a4c6933..17f714b 100644 --- a/src/templates/entity.mst +++ b/src/templates/entity.mst @@ -38,7 +38,6 @@ export class {{toEntityName tscName}}{{#activeRecord}} extends BaseEntity{{/acti {{#if generateConstructor}}{{>Constructor entityName=tscName}}{{/if~}} } {{/inline}} - import {BaseEntity,Column,Entity,Index,JoinColumn,JoinTable,ManyToMany,ManyToOne,OneToMany,OneToOne,PrimaryColumn,PrimaryGeneratedColumn,RelationId} from "typeorm"; {{#fileImports}}{{> Import}}{{/fileImports~}}