Skip to content

Instantly share code, notes, and snippets.

@dsherret
Created February 6, 2016 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dsherret/927d627baa7340d01546 to your computer and use it in GitHub Desktop.
Save dsherret/927d627baa7340d01546 to your computer and use it in GitHub Desktop.
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];
}
}
@dsherret
Copy link
Author

dsherret commented Feb 6, 2016

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:

import {ClassDefinition} from "./../definitions";
import {Scope} from "./../definitions";

It would stop failing when you change it to:

import {ClassDefinition, Scope} from "./../definitions"

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment