Skip to content
This repository has been archived by the owner on Aug 18, 2021. It is now read-only.

Use @babel/core#parse #711

Merged
merged 22 commits into from Jan 10, 2019
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
@@ -1 +1,2 @@
!.*.js
test/fixtures
16 changes: 8 additions & 8 deletions .eslintrc.js
@@ -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: {
Expand All @@ -19,8 +19,8 @@ module.exports = {
{
files: ["test/**/*"],
env: {
mocha: true
}
}
]
mocha: true,
},
},
],
};
140 changes: 73 additions & 67 deletions README.md
Expand Up @@ -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).

**.eslintrc.js**

```json
{
"parser": "babel-eslint",
"rules": {
"strict": 0
}
}
```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.

**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`.

### Additional parser configuration

### 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.
- `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.

**.eslintrc**

```json
{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": false,
"codeFrame": true
}
}
- `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.js**

```js
module.exports = {
parser: "babel-eslint",
parserOptions: {
sourceType: "module",
allowImportExportEverywhere: false,
ecmaFeatures: {
globalReturn: false,
},
babelOptions: {
configFile: "path/to/config.js",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fantastic. Very important for toolkits that encapsulate eslint config. Thank you for adding this feature 💯

},
},
};
```

### 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).
2 changes: 1 addition & 1 deletion lib/analyze-scope.js
@@ -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");
Expand Down
2 changes: 1 addition & 1 deletion lib/babylon-to-espree/toAST.js
@@ -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) {
Expand Down
21 changes: 21 additions & 0 deletions lib/index.js
@@ -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 =
Expand Down
96 changes: 28 additions & 68 deletions lib/parse.js
@@ -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,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should probably pass through all the options that can directly influence a config:

  • cwd
  • root
  • rootMode
  • envName
  • configFile
  • babelrc
  • babelrcRoots
  • extends
  • env
  • overrides
  • test
  • include
  • exclude
  • ignore
  • only

It would be great to also set

caller: {
  name: "babel-eslint",
},

Copy link
Member Author

@kaicataldo kaicataldo Jan 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have updated this, but I'm wondering if we do really want the config merging options here - shouldn't we be able to just provide the config loading options that would point to the config file that could then contain the config merging options? This would avoid duplication in the .eslintrc.js and babel.config.js files.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think

cwd
root
rootMode
envName
configFile
babelrc
babelrcRoots

are important to have since they affect the actual process of loading config files. The rest are not strictly necessary, but it seems like support for them might as well be included.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally would prefer to start with fewer rather than more options (especially since this project is already difficult to maintain), but am happy to defer to what you think is best. 👍

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.babelrRoots,
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;
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion lib/visitor-keys.js
@@ -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(
Expand Down