Skip to content

Instantly share code, notes, and snippets.

@Quramy
Last active July 18, 2019 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Quramy/d1473603c1e00132d71de573eb5d2cae to your computer and use it in GitHub Desktop.
Save Quramy/d1473603c1e00132d71de573eb5d2cae to your computer and use it in GitHub Desktop.
How to get ESLint result from TypeScript AST using @typescript-eslint/typescript-estree
import * as ts from "typescript";
import { SourceCode, Linter, AST } from "eslint";
import { Extra } from "@typescript-eslint/typescript-estree/dist/parser-options";
import convert from "@typescript-eslint/typescript-estree/dist/ast-converter";
function initExtra() {
return {
tokens: null,
range: false,
loc: false,
comment: false,
comments: [],
strict: false,
jsx: false,
useJSXTextNode: false,
log: console.log,
projects: [],
errorOnUnknownASTType: false,
errorOnTypeScriptSyntacticAndSemanticIssues: false,
code: "",
tsconfigRootDir: process.cwd(),
extraFileExtensions: [],
preserveNodeMaps: undefined,
} as Extra;
}
function getEslintMessageFromTypeScriptAST(tsSourceCode: ts.SourceFile) {
const code = tsSourceCode.getFullText();
// Create options for converter
const extra = initExtra();
// They're needed to pass the converter result to eslint's SourceCode
extra.tokens = [];
extra.comment = true;
extra.comments = [];
extra.code = code;
// Convert from TypeScript AST to estree AST
const { estree } = convert(tsSourceCode, extra, false);
// Verfy using ESLint linter
const linter = new Linter();
return linter.verify(
new SourceCode(code, estree as AST.Program),
{
rules: {
semi: 2,
},
},
{
filename: "test.ts",
},
);
}
const content = `
// missing semicolon
const hoge = 1
`;
const tsSourceCode = ts.createSourceFile("test.ts", content, ts.ScriptTarget.Latest, true);
const eslintResult = getEslintMessageFromTypeScriptAST(tsSourceCode);
eslintResult.forEach(({ message }) => console.log(message));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment