Use @babel/core#parse (babel/babel-eslint#711)

This commit is contained in:
Kai Cataldo 2019-01-10 15:25:00 -05:00
parent bede064c0b
commit 47de99e1b8
17 changed files with 1148 additions and 283 deletions

View File

@ -1 +1,2 @@
!.*.js
test/fixtures

View File

@ -1,12 +1,12 @@
"use strict";
module.exports = {
root: true,
extends: "babel",
"plugins": [
"prettier"
],
plugins: ["prettier"],
rules: {
"max-len": "off",
"strict": "error",
strict: "error",
"prettier/prettier": "error",
},
env: {
@ -19,8 +19,8 @@ module.exports = {
{
files: ["test/**/*"],
env: {
mocha: true
}
}
]
mocha: true,
},
},
],
};

View File

@ -3,101 +3,107 @@
**babel-eslint** allows you to lint **ALL** valid Babel code with the fantastic
[ESLint](https://github.com/eslint/eslint).
### Why Use babel-eslint
## Breaking change in v11.x.x
You only need to use babel-eslint if you are using types (Flow) or experimental features not supported in ESLint itself yet. Otherwise try the default parser (you don't have to use it just because you are using Babel).
As of the v11.x.x release, babel-eslint now requires Babel as a peer dependency and expects a valid [Babel configuration file](https://babeljs.io/docs/en/configuration) to exist. This ensures that the same Babel configuration is used during both linting and compilation.
---
## When should I use babel-eslint?
> If there is an issue, first check if it can be reproduced with the regular parser or with the latest versions of `eslint` and `babel-eslint`!
ESLint's default parser and core rules [only suppport the latest final ECMAScript standard](https://github.com/eslint/eslint/blob/a675c89573836adaf108a932696b061946abf1e6/README.md#what-about-experimental-features) and do not support experimental (such as new features) and non-standard (such as Flow or TypeScript types) syntax provided by Babel. babel-eslint is a parser that allows ESLint to run on source code that is transformed by Babel.
For questions and support please visit the [`#discussion`](https://babeljs.slack.com/messages/discussion/) babel slack channel (sign up [here](https://github.com/babel/notes/issues/38)) or eslint [gitter](https://gitter.im/eslint/eslint)!
> Note that the `ecmaFeatures` config property may still be required for ESLint to work properly with features not in ECMAScript 5 by default. Examples are `globalReturn` and `modules`).
## Known Issues
Flow:
> Check out [eslint-plugin-flowtype](https://github.com/gajus/eslint-plugin-flowtype): An `eslint` plugin that makes flow type annotations global variables and marks declarations as used. Solves the problem of false positives with `no-undef` and `no-unused-vars`.
- `no-undef` for global flow types: `ReactElement`, `ReactClass` [#130](https://github.com/babel/babel-eslint/issues/130#issuecomment-111215076)
- Workaround: define types as globals in `.eslintrc` or define types and import them `import type ReactElement from './types'`
- `no-unused-vars/no-undef` with Flow declarations (`declare module A {}`) [#132](https://github.com/babel/babel-eslint/issues/132#issuecomment-112815926)
Modules/strict mode
- `no-unused-vars: [2, {vars: local}]` [#136](https://github.com/babel/babel-eslint/issues/136)
Please check out [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) for React/JSX issues
- `no-unused-vars` with jsx
Please check out [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) for other issues
**Note:** You only need to use babel-eslint if you are using Babel to transform your code. If this is not the case, please use the relevant parser for your chosen flavor of ECMAScript (note that the default parser supports all non-experimental syntax as well as JSX).
## How does it work?
ESLint allows custom parsers. This is great but some of the syntax nodes that Babel supports
aren't supported by ESLint. When using this plugin, ESLint is monkeypatched and your code is
transformed into code that ESLint can understand. All location info such as line numbers,
ESLint allows for the use of [custom parsers](https://eslint.org/docs/developer-guide/working-with-custom-parsers). When using this plugin, your code is parsed by Babel's parser (using the configuration specified in your [Babel configuration file](https://babeljs.io/docs/en/configuration)) and the resulting AST is
transformed into an [ESTree](https://github.com/estree/estree)-compliant structure that ESLint can understand. All location info such as line numbers,
columns is also retained so you can track down errors with ease.
Basically `babel-eslint` exports an [`index.js`](/lib/index.js) that a linter can use.
It just needs to export a `parse` method that takes in a string of code and outputs an AST.
**Note:** ESLint's core rules do not support experimental syntax and may therefore not work as expected when using babel-eslint. Please use the companion [`eslint-plugin-babel`](https://github.com/babel/eslint-plugin-babel) plugin for core rules that you have issues with.
## Usage
### Supported ESLint versions
ESLint | babel-eslint
------------ | -------------
4.x | >= 6.x
3.x | >= 6.x
2.x | >= 6.x
1.x | >= 5.x
### Install
Ensure that you have substituted the correct version lock for `eslint` and `babel-eslint` into this command:
### Installation
```sh
$ npm install eslint@4.x babel-eslint@8 --save-dev
$ npm install eslint babel-eslint --save-dev
# or
$ yarn add eslint@4.x babel-eslint@8 -D
$ yarn add eslint babel-eslint -D
```
**Note:** babel-eslint requires `babel/core@>=7.2.0` and a valid Babel configuration file to run. If you do not have this already set up, please see the [Babel Usage Guide](https://babeljs.io/docs/en/usage).
### Setup
**.eslintrc**
To use babel-eslint, `"babel-eslint"` must be specified as the `parser` in your ESLint configuration file (see [here](https://eslint.org/docs/user-guide/configuring#specifying-parser) for more detailed information).
```json
{
"parser": "babel-eslint",
"rules": {
"strict": 0
}
}
**.eslintrc.js**
```js
module.exports = {
parser: "babel-eslint",
};
```
Check out the [ESLint docs](http://eslint.org/docs/rules/) for all possible rules.
With the parser set, your configuration can be configured as described in the [Configuring ESLint](https://eslint.org/docs/user-guide/configuring) documentation.
### Configuration
**Note:** The `parserOptions` described in the [official documentation](https://eslint.org/docs/user-guide/configuring#specifying-parser-options) are for the default parser and are not necessarily supported by babel-eslint. Please see the section directly below for supported `parserOptions`.
- `sourceType` can be set to `'module'`(default) or `'script'` if your code isn't using ECMAScript modules.
### Additional parser configuration
Additional configuration options can be set in your ESLint configuration under the `parserOptions` key. Please note that the `ecmaFeatures` config property may still be required for ESLint to work properly with features not in ECMAScript 5 by default.
- `sourceType` can be set to `"module"`(default) or `"script"` if your code isn't using ECMAScript modules.
- `allowImportExportEverywhere` (default `false`) can be set to `true` to allow import and export declarations to appear anywhere a statement is allowed if your build environment supports that. Otherwise import and export declarations can only appear at a program's top level.
- `codeFrame` (default `true`) can be set to `false` to disable the code frame in the reporter. This is useful since some eslint formatters don't play well with it.
- `ecmaFeatures.globalReturn` (default `false`) allow return statements in the global scope when used with `sourceType: "script"`.
- `babelOptions` passes through Babel's configuration [loading](https://babeljs.io/docs/en/options#config-loading-options) and [merging](https://babeljs.io/docs/en/options#config-merging-options) options (for instance, in case of a monorepo). When not defined, babel-eslint will use Babel's default configuration file resolution logic.
**.eslintrc**
**.eslintrc.js**
```json
{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": false,
"codeFrame": true
}
}
```js
module.exports = {
parser: "babel-eslint",
parserOptions: {
sourceType: "module",
allowImportExportEverywhere: false,
ecmaFeatures: {
globalReturn: false,
},
babelOptions: {
configFile: "path/to/config.js",
},
},
};
```
### Run
```sh
$ eslint your-files-here
$ ./node_modules/.bin/eslint yourfile.js
```
## Known issues
Flow:
> Check out [eslint-plugin-flowtype](https://github.com/gajus/eslint-plugin-flowtype): An `eslint` plugin that makes flow type annotations global variables and marks declarations as used. Solves the problem of false positives with `no-undef` and `no-unused-vars`.
- `no-undef` for global flow types: `ReactElement`, `ReactClass` [#130](https://github.com/babel/babel-eslint/issues/130#issuecomment-111215076)
- Workaround: define types as globals in `.eslintrc` or define types and import them `import type ReactElement from './types'`
- `no-unused-vars/no-undef` with Flow declarations (`declare module A {}`) [#132](https://github.com/babel/babel-eslint/issues/132#issuecomment-112815926)
Modules/strict mode
- `no-unused-vars: ["error", { vars: local }]` [#136](https://github.com/babel/babel-eslint/issues/136)
Please check out [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) for React/JSX issues.
- `no-unused-vars` with jsx
Please check out [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) for other issues.
## Questions and support
If you have an issue, please first check if it can be reproduced with the default parser and with the latest versions of `eslint` and `babel-eslint`. If it is not reproducible with the default parser, it is most likely an issue with babel-eslint.
For questions and support please visit the [`#discussion`](https://babeljs.slack.com/messages/discussion/) Babel Slack channel (sign up [here](https://github.com/babel/notes/issues/38)) or the ESLint [Gitter](https://gitter.im/eslint/eslint).

View File

@ -1,6 +1,6 @@
"use strict";
const t = require("@babel/types");
const t = require("@babel/core").types;
const escope = require("eslint-scope");
const Definition = require("eslint-scope/lib/definition").Definition;
const OriginalPatternVisitor = require("eslint-scope/lib/pattern-visitor");

View File

@ -1,6 +1,6 @@
"use strict";
const t = require("@babel/types");
const t = require("@babel/core").types;
const convertComments = require("./convertComments");
module.exports = function(ast, traverse, code) {

View File

@ -1,11 +1,32 @@
"use strict";
const semver = require("semver");
const babelCore = require("@babel/core");
const packageJson = require("../package.json");
const CURRENT_BABEL_VERSION = babelCore.version;
const SUPPORTED_BABEL_VERSION_RANGE =
packageJson.peerDependencies["@babel/core"];
const IS_RUNNING_SUPPORTED_VERSION = semver.satisfies(
CURRENT_BABEL_VERSION,
SUPPORTED_BABEL_VERSION_RANGE
);
exports.parse = function(code, options) {
return exports.parseForESLint(code, options).ast;
};
exports.parseForESLint = function(code, options) {
if (!IS_RUNNING_SUPPORTED_VERSION) {
throw new Error(
`babel-eslint@${
packageJson.version
} does not support @babel/core@${CURRENT_BABEL_VERSION}. Please downgrade to babel-eslint@^10 or upgrade to @babel/core@${SUPPORTED_BABEL_VERSION_RANGE}`
);
}
options = options || {};
options.babelOptions = options.babelOptions || {};
options.ecmaVersion = options.ecmaVersion || 2018;
options.sourceType = options.sourceType || "module";
options.allowImportExportEverywhere =

View File

@ -1,54 +1,38 @@
"use strict";
const babylonToEspree = require("./babylon-to-espree");
const parse = require("@babel/parser").parse;
const tt = require("@babel/parser").tokTypes;
const traverse = require("@babel/traverse").default;
const codeFrameColumns = require("@babel/code-frame").codeFrameColumns;
const { parseSync: parse, tokTypes: tt, traverse } = require("@babel/core");
module.exports = function(code, options) {
const legacyDecorators =
options.ecmaFeatures && options.ecmaFeatures.legacyDecorators;
const opts = {
codeFrame: options.hasOwnProperty("codeFrame") ? options.codeFrame : true,
sourceType: options.sourceType,
allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
ranges: true,
tokens: true,
plugins: [
["flow", { all: true }],
"jsx",
"estree",
"asyncFunctions",
"asyncGenerators",
"classConstructorCall",
"classProperties",
legacyDecorators
? "decorators-legacy"
: ["decorators", { decoratorsBeforeExport: false }],
"doExpressions",
"exponentiationOperator",
"exportDefaultFrom",
"exportNamespaceFrom",
"functionBind",
"functionSent",
"objectRestSpread",
"trailingFunctionCommas",
"dynamicImport",
"numericSeparator",
"optionalChaining",
"importMeta",
"classPrivateProperties",
"bigInt",
"optionalCatchBinding",
"throwExpressions",
["pipelineOperator", { proposal: "minimal" }],
"nullishCoalescingOperator",
"logicalAssignment",
],
filename: options.filePath,
cwd: options.babelOptions.cwd,
root: options.babelOptions.root,
rootMode: options.babelOptions.rootMode,
envName: options.babelOptions.envName,
configFile: options.babelOptions.configFile,
babelrc: options.babelOptions.babelrc,
babelrcRoots: options.babelOptions.babelrcRoots,
extends: options.babelOptions.extends,
env: options.babelOptions.env,
overrides: options.babelOptions.overrides,
test: options.babelOptions.test,
include: options.babelOptions.include,
exclude: options.babelOptions.exclude,
ignore: options.babelOptions.ignore,
only: options.babelOptions.only,
parserOpts: {
allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
ranges: true,
tokens: true,
plugins: ["estree"],
},
caller: {
name: "babel-eslint",
},
};
let ast;
@ -58,30 +42,6 @@ module.exports = function(code, options) {
if (err instanceof SyntaxError) {
err.lineNumber = err.loc.line;
err.column = err.loc.column;
if (opts.codeFrame) {
err.lineNumber = err.loc.line;
err.column = err.loc.column + 1;
// remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
err.message =
"Line " +
err.lineNumber +
": " +
err.message.replace(/ \((\d+):(\d+)\)$/, "") +
// add codeframe
"\n\n" +
codeFrameColumns(
code,
{
start: {
line: err.lineNumber,
column: err.column,
},
},
{ highlightCode: true }
);
}
}
throw err;

View File

@ -1,6 +1,6 @@
"use strict";
const BABEL_VISITOR_KEYS = require("@babel/types").VISITOR_KEYS;
const BABEL_VISITOR_KEYS = require("@babel/core").types.VISITOR_KEYS;
const ESLINT_VISITOR_KEYS = require("eslint-visitor-keys").KEYS;
module.exports = Object.assign(

View File

@ -2,44 +2,56 @@
"name": "babel-eslint",
"version": "10.0.1",
"description": "Custom parser for ESLint",
"main": "lib/index.js",
"files": [
"lib"
],
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel-eslint.git"
},
"dependencies": {
"@babel/code-frame": "^7.0.0",
"@babel/parser": "^7.0.0",
"@babel/traverse": "^7.0.0",
"@babel/types": "^7.0.0",
"eslint-scope": "3.7.1",
"eslint-visitor-keys": "^1.0.0"
},
"scripts": {
"test": "npm run lint && npm run test-only",
"test-only": "mocha && mocha --require test/fixtures/preprocess-to-patch.js",
"lint": "eslint lib test",
"fix": "eslint lib test --fix",
"precommit": "lint-staged",
"preversion": "npm test",
"changelog": "git log `git describe --tags --abbrev=0`..HEAD --pretty=format:' * %s (%an)' | grep -v 'Merge pull request'"
},
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"license": "MIT",
"engines": {
"node": ">=6"
},
"bugs": {
"url": "https://github.com/babel/babel-eslint/issues"
},
"homepage": "https://github.com/babel/babel-eslint",
"scripts": {
"test": "npm run lint && npm run test-only",
"test-only": "cd test && mocha --require fixtures/preprocess-to-patch.js specs && cd -",
"lint": "eslint .",
"lint-fix": "npm run lint -- --fix",
"precommit": "lint-staged",
"preversion": "npm test",
"changelog": "git log `git describe --tags --abbrev=0`..HEAD --pretty=format:' * %s (%an)' | grep -v 'Merge pull request'"
},
"engines": {
"node": ">=6"
},
"main": "lib/index.js",
"files": [
"lib"
],
"peerDependencies": {
"@babel/core": ">=7.2.0",
"eslint": ">= 4.12.1"
},
"dependencies": {
"eslint-scope": "3.7.1",
"eslint-visitor-keys": "^1.0.0",
"semver": "^5.6.0"
},
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/plugin-proposal-decorators": "^7.1.2",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.0.0",
"@babel/plugin-proposal-optional-chaining": "^7.0.0",
"@babel/plugin-proposal-pipeline-operator": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/plugin-syntax-export-default-from": "^7.0.0",
"@babel/plugin-syntax-export-namespace-from": "^7.0.0",
"@babel/plugin-syntax-import-meta": "^7.0.0",
"@babel/plugin-syntax-numeric-separator": "^7.0.0",
"@babel/preset-env": "^7.1.5",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^8.2.6",
"dedent": "^0.7.0",
"eslint": "^5.6.0",

View File

@ -0,0 +1,21 @@
"use strict";
module.exports = {
presets: [
["@babel/preset-env", { forceAllTransforms: true }],
["@babel/preset-flow", { all: true }],
"@babel/preset-react",
],
plugins: [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
"@babel/plugin-syntax-export-default-from",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-syntax-numeric-separator",
"@babel/plugin-syntax-export-namespace-from",
["@babel/plugin-proposal-decorators", { decoratorsBeforeExport: false }],
["@babel/plugin-proposal-pipeline-operator", { proposal: "minimal" }],
],
};

View File

@ -0,0 +1,6 @@
"use strict";
module.exports = {
presets: [["@babel/preset-env", { forceAllTransforms: true }]],
plugins: [["@babel/plugin-proposal-decorators", { legacy: true }]],
};

View File

@ -1,4 +1,4 @@
"use strict"
"use strict";
// Checks if the source ast implements the target ast. Ignores extra keys on source ast
module.exports = function assertImplementsAST(target, source, path) {
@ -24,8 +24,9 @@ module.exports = function assertImplementsAST(target, source, path) {
target.constructor.name !== source.constructor.name
) {
error(
`object have different constructors (${target.constructor
.name} !== ${source.constructor.name}`
`object have different constructors (${target.constructor.name} !== ${
source.constructor.name
}`
);
} else if (typeA === "object") {
const keysTarget = Object.keys(target);

View File

@ -1,12 +1,12 @@
"use strict";
const assert = require("assert");
const babelEslint = require("..");
const babelEslint = require("../..");
const espree = require("espree");
const escope = require("eslint-scope");
const util = require("util");
const unpad = require("dedent");
const assertImplementsAST = require("./fixtures/assert-implements-ast");
const assertImplementsAST = require("../helpers/assert-implements-ast");
function lookup(obj, keypath, backwardsDepth) {
if (!keypath) {

View File

@ -6,14 +6,14 @@ const fs = require("fs");
const path = require("path");
const paths = {
fixtures: path.join(__dirname, "fixtures", "rules"),
fixtures: path.join(__dirname, "..", "fixtures", "rules"),
};
const encoding = "utf8";
const errorLevel = 2;
const baseEslintOpts = {
parser: require.resolve(".."),
parser: require.resolve("../.."),
parserOptions: {
sourceType: "script",
},
@ -222,64 +222,4 @@ function strictSuite() {
});
// it
});
// describe
describe('When "codeFrame"', () => {
// Strip chalk colors, these are not relevant for the test
const stripAnsi = str =>
str.replace(
// eslint-disable-next-line no-control-regex
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
""
);
it("should display codeFrame when option is absent", done => {
lint(
{
fixture: ["syntax-error"],
eslint: baseEslintOpts,
},
(err, report) => {
if (err) return done(err);
assert(stripAnsi(report[0].message).indexOf("^\n 5 |") > -1);
done();
}
);
});
it("should display codeFrame when option is true", done => {
lint(
{
fixture: ["syntax-error"],
eslint: Object.assign({}, baseEslintOpts, {
parserOptions: {
codeFrame: true,
},
}),
},
(err, report) => {
if (err) return done(err);
assert(stripAnsi(report[0].message).indexOf("^\n 5 |") > -1);
done();
}
);
});
it("should not display codeFrame when option is false", done => {
lint(
{
fixture: ["syntax-error"],
eslint: Object.assign({}, baseEslintOpts, {
parserOptions: {
codeFrame: false,
},
}),
},
(err, report) => {
if (err) return done(err);
assert(stripAnsi(report[0].message).indexOf("^\n 5 |") === -1);
done();
}
);
});
});
}

View File

@ -1,6 +1,7 @@
"use strict";
const eslint = require("eslint");
const path = require("path");
const unpad = require("dedent");
function verifyAndAssertMessagesWithSpecificESLint(
@ -12,20 +13,17 @@ function verifyAndAssertMessagesWithSpecificESLint(
linter
) {
const config = {
parser: require.resolve(".."),
parser: require.resolve("../.."),
rules,
env: {
node: true,
es6: true,
},
parserOptions: {
ecmaVersion: 2018,
sourceType,
ecmaFeatures: {
jsx: true,
experimentalObjectRestSpread: true,
globalReturn: true,
},
sourceType,
},
};
@ -1155,10 +1153,13 @@ describe("verify", () => {
) {
const overrideConfig = {
parserOptions: {
ecmaFeatures: {
legacyDecorators: true,
},
sourceType,
babelOptions: {
configFile: path.resolve(
__dirname,
"../fixtures/config/babel.config.decorators-legacy.js"
),
},
},
};
return verifyAndAssertMessages(

View File

@ -2,17 +2,17 @@
const eslint = require("eslint");
const assert = require("assert");
const babelEslint = require("..");
const babelEslint = require("../..");
const espree = require("espree");
const assertImplementsAST = require("./fixtures/assert-implements-ast");
const assertImplementsAST = require("../helpers/assert-implements-ast");
describe("https://github.com/babel/babel-eslint/issues/558", () => {
it("don't crash with eslint-plugin-import", () => {
const engine = new eslint.CLIEngine({ ignore: false });
engine.executeOnFiles([
"test/fixtures/eslint-plugin-import/a.js",
"test/fixtures/eslint-plugin-import/b.js",
"test/fixtures/eslint-plugin-import/c.js",
"../test/fixtures/eslint-plugin-import/a.js",
"../test/fixtures/eslint-plugin-import/b.js",
"../test/fixtures/eslint-plugin-import/c.js",
]);
});

File diff suppressed because it is too large Load Diff