Last active
December 17, 2018 22:13
-
-
Save sompylasar/8d95c581f10597addcd4b9855ee584fa to your computer and use it in GitHub Desktop.
Branching ESLint parser to consume both TypeScript (via typescript-eslint-parser) and JavaScript (via babel-eslint). Usage: in .eslintrc, "parser": "./eslintParserForTypeScriptAndJavaScript.js"
This file contains 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
/* eslint-disable func-names, prefer-arrow-callback */ | |
function isTypeScriptFilePath(filePath) { | |
return /\.tsx?$/.test(filePath); | |
} | |
function isTypeScriptCode(text) { | |
return ( | |
/^\s*((declare\s+module)|(interface))\s+/m.test(text) | |
); | |
} | |
function shouldUseTypeScriptParser(text, parserOptions) { | |
return ( | |
isTypeScriptFilePath(parserOptions.filePath) | |
// HACK(@sompylasar): While waiting for the updated `eslint-plugin-import` to be released, have to detect TypeScript by file content. https://github.com/benmosher/eslint-plugin-import/pull/840 | |
// TODO(@sompylasar): Remove this hack and update `eslint-plugin-import` as soon as the PR is merged and released: https://github.com/benmosher/eslint-plugin-import/pull/840 | |
|| (!parserOptions.filePath && isTypeScriptCode(text)) | |
); | |
} | |
function parseTypeScript(text, parserOptions) { | |
const ast = require('typescript-eslint-parser').parse(text, parserOptions); | |
// WORKAROUND(@sompylasar): Drop `declare module` to prevent its contents from triggering `no-undef`. https://github.com/eslint/typescript-eslint-parser/issues/77#issuecomment-293581001 | |
ast.body = ast.body.filter(function (node) { | |
return (node.type !== 'TSModuleDeclaration'); | |
}); | |
// WORKAROUND(@sompylasar): Failsafe for `eslint-plugin-import` TypeError: Cannot read property 'some' of undefined when `ast.comments` is missing on the AST. https://github.com/benmosher/eslint-plugin-import/issues/842 | |
ast.comments = ast.comments || []; | |
return ast; | |
} | |
function parseJavaScript(text, parserOptions) { | |
const ast = require('babel-eslint').parse(text, parserOptions); | |
return ast; | |
} | |
module.exports = { | |
parse: function (text, parserOptions) { | |
if (shouldUseTypeScriptParser(text, parserOptions)) { | |
return parseTypeScript(text, parserOptions); | |
} | |
return parseJavaScript(text, parserOptions); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment