Created
February 6, 2016 04:55
-
-
Save dsherret/927d627baa7340d01546 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as ts from "typescript"; | |
import * as Lint from "tslint/lib/lint"; | |
export class Rule extends Lint.Rules.AbstractRule { | |
static FAILURE_STRING = "duplicate imports from same file forbidden"; | |
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { | |
return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions())); | |
} | |
} | |
class NoDuplicateImportsFromSameFileWalker extends Lint.RuleWalker { | |
private fileImportsByFileName: { [fileName: string]: { [importName: string]: boolean } } = {}; | |
visitImportDeclaration(node: ts.ImportDeclaration) { | |
const sourceFile = node.parent as ts.SourceFile; | |
const fileImports = this.getFileImports(sourceFile.fileName); | |
const importPath = (node.moduleSpecifier as any).text as string; | |
if (fileImports[importPath] != null) { | |
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING)); | |
} | |
else { | |
fileImports[importPath] = true; | |
} | |
super.visitImportDeclaration(node); | |
} | |
private getFileImports(fileName: string) { | |
this.fileImportsByFileName[fileName] = this.fileImportsByFileName[fileName] || {}; | |
return this.fileImportsByFileName[fileName]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a custom tslint rule to prevent duplicate imports from the same file in a file. For example, the following would create a failure:
It would stop failing when you change it to:
I have not tested this with default exports yet because I mainly use named exports for reasons I have outlined in this Stack Overflow answer.
Read about using custom rules here.