Giter Club home page Giter Club logo

eslint-plugin-babel's Introduction

eslint-plugin-babel

NOTE: eslint-plugin-babel is now @babel/eslint-plugin and has moved into the Babel monorepo.

An eslint plugin companion to babel-eslint. babel-eslint does a great job at adapting eslint for use with Babel, but it can't change the built in rules to support experimental features. eslint-plugin-babel re-implements problematic rules so they do not give false positives or negatives.

Requires Node 4 or greater

Install

npm install eslint-plugin-babel --save-dev

Load the plugin in your .eslintrc file:

{
  "plugins": [
    "babel"
  ]
}

Finally enable all the rules you would like to use (remember to disable the original ones as well!).

{
  "rules": {
    "babel/new-cap": 1,
    "babel/camelcase": 1,
    "babel/no-invalid-this": 1,
    "babel/object-curly-spacing": 1,
    "babel/quotes": 1,
    "babel/semi": 1,
    "babel/no-unused-expressions": 1,
    "babel/valid-typeof": 1
  }
}

Rules

Each rule corresponds to a core eslint rule, and has the same options.

๐Ÿ› : means it's autofixable with --fix.

  • babel/new-cap: Ignores capitalized decorators (@Decorator)
  • babel/camelcase: doesn't complain about optional chaining (var foo = bar?.a_b;)
  • babel/no-invalid-this: doesn't fail when inside class properties (class A { a = this.b; })
  • babel/object-curly-spacing: doesn't complain about export x from "mod"; or export * as x from "mod"; (๐Ÿ› )
  • babel/quotes: doesn't complain about JSX fragment shorthand syntax (<>foo</>;)
  • babel/semi: doesn't fail when using for await (let something of {}). Includes class properties (๐Ÿ› )
  • babel/no-unused-expressions: doesn't fail when using do expressions or optional chaining (a?.b()).
  • babel/valid-typeof: doesn't complain when used with BigInt (typeof BigInt(9007199254740991) === 'bigint').

Deprecated

Rule Notes
babel/generator-star-spacing Use generator-star-spacing since [email protected]
babel/object-shorthand Use object-shorthand since [email protected]
babel/arrow-parens Use arrow-parens since [email protected]
babel/func-params-comma-dangle Use comma-dangle since [email protected]
babel/array-bracket-spacing Use array-bracket-spacing since [email protected]
babel/flow-object-type Use flowtype/object-type-delimiter since [email protected]
babel/no-await-in-loop Use no-await-in-loop since [email protected]

eslint-plugin-babel's People

Contributors

aaronjensen avatar amilajack avatar aruberto avatar daltones avatar dependabot[bot] avatar elstgav avatar existentialism avatar fergald avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hawkrives avatar hzoo avatar jlhwung avatar jquense avatar kaicataldo avatar kobelb avatar legneato avatar lehni avatar lemonmade avatar lyleunderwood avatar mathieumg avatar nmote avatar pascalduez avatar preco21 avatar simonkotwicz avatar ssorallen avatar villesau avatar wagerfield avatar zaygraveyard avatar zertosh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eslint-plugin-babel's Issues

Catch unary operator after keyword await as error

To invert the boolean value (or any unary operator, such as ~ or - for numbers) returned from promise with await, we should put the operator before the await keyword rather than after. But this is counterintuitive and error-prone.

e.g.

function returnFalse() {
  return Promise.resolve(false);
}

async function test() {
  if(await !returnFalse()) {
    console.log('ok');
  }  
}

test();

We might expect ok to be displayed, but it never does. Since we apply ! on the promise return by async function, which is meaningless in most cases. So it would be nice if any code that apply ! after await rather than before.

Here is the correct test():

async function test() {
  if(! await returnFalse()) {
    console.log('ok');
  }  
}

I think it will be a general issue when writing code with async/await. And I think linter should check fo r this case.

Question about no-await-in-loop

What's the purpose of this rule? Isn't the ability to pause a function anywhere you want (even mid loop) the whole point of async functions? I don't get why someone would want to guard against this, I do it all the time. Is there an issue I'm not aware of?

generator-star-spacing - Unexpected space after *

I have a following code with default rule setting ("before").

async lockCallback(normalizedProfile, token) {
}

Fails with Unexpected space after * babel/generator-star-spacing

Using "after" fixes first issue, but causes another two for the following code

export function *iterateChildren() {
}
warning  Unexpected space before *  babel/generator-star-spacing
warning  Missing space after *      babel/generator-star-spacing

Using "both" or "neither" is unwanted, but essentially fixes the first issue.

"eslint": "~1.9.0",
"eslint-plugin-babel": "^3.1.0",
"eslint-plugin-react": "^3.16.1",
"babel": "~5.8.23",
"babel-core": "~5.8.34",
"babel-eslint": "~4.1.4",

`no-multi-spaces` does not support ES7 class properties

In my team we like to align variable declarations, so we use no-multi-spaces to enforce that.
But we recently started working with babel-eslint to use ES7 features and our lint fails when we try to align class properties.

Code:

export class Login extends React.Component {
  canSubmit   = false;
  serverError = null;
}

.eslintrc:

{
  "plugins": [
    "react",
    "babel"
  ],

  "extends": ["eslint:recommended", "plugin:react/recommended"],

  "env": {
    "es6": true,
    "browser": true
  },

  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 6,
    "ecmaFeatures": {
      "jsx": true
    },
    "sourceType": "module"
  },

  "rules": {
    "no-multi-spaces": [1, {
      "exceptions": {
        "VariableDeclarator": true,
        "ImportDeclaration": true,
        "ImportSpecifier": true,
        "AssignmentExpression": true
      }
    }]
  }
}

Warning:

warning  Multiple spaces found before '='        no-multi-spaces

Infix spacing for static class properties

ESLint's space-infix-ops will catch:

/*eslint space-infix-ops: "error"*/

var a =2;

But, it won't catch a static property assignment:

/*eslint space-infix-ops: "error"*/

export class foo {
    static a =2;
}

I'd like to propose an extension to the space-infix-ops rule which would enforce spacing around assignment operators of static class properties.

`comma-dangle` on for loop + destructuring declaration

code:

let x = [3, 2, 1, 0]
for (let [value, ] of x.entries()) {
  console.log(value)
}

error:

2:10  error  Expected consistent spacing  standard/array-bracket-even-spacing
2:16  error  Unexpected trailing comma    comma-dangle

Add a decorator-undef-shorthand-prop rule.

The following is a nice idiom using decorators:

var Person = Model.extend({
  @attr firstName,
  @attr lastName
});

But eslint will then warn: error: "firstName" is not defined. (no-undef).

So it might be a good case to add a rule that allows this.

Deprecate upstreamed rules

The following rules have had their effects added upstream:

  • babel/generator-star-spacing: ESLint now supports async/await, and the upstream rule works fine
  • babel/object-shorthand: This works upstream now
  • babel/arrow-parens: async support works upstream; the only difference now is this handles Flow annotations and doesn't tell me that I have unnecessary parens when using (foo: mixed) => foo, and as such should probably go in eslint-plugin-flowtype
  • babel/func-params-comma-dangle: Supported in comma-dangle as of ESLint v3.8.0

It would be ideal if we could warn when these rules are enabled, and look to removing them in the future.

There's currently no fully built-in way to warn on deprecated rules (see eslint/eslint#7443), but the pattern in eslint-plugin-react looks pretty good: https://github.com/yannickcr/eslint-plugin-react/blob/e1697996ff494bf584057418e2974ece7f3d99d8/lib/rules/wrap-multilines.js#L45-L53.

Update eslint/babel-eslint versions

babel-eslint to 6.x, eslint to 2.x (for testing), use phantomjs pre-built

Will probably have to copy the eslint tests from before because of the config changes.. (:cry:)

Does this work in VS Code?

Like mentioned in the title, I can't get it to work in VS Code. More exactly, it fails when trying to parse ES7 syntax such as

async function a () {
   ...
}

or that also:

async () => {
   ...
}

I have used the same configuration like defined in the README https://github.com/babel/eslint-plugin-babel with the plugins babel and the list of rules.

In Atom, this works well though.

Is it related to the plugin, or related to VS Code?

async / await

Do I need this plugin to use async await with eslint? I can't seem to get it to work.

Object spread syntax not recognized

This is almost certainly my error, but after fiddling around for an hour I have not been able to figure out a solution. I'm trying to get object spread linting working with the following line of code:

const modelState = { ...defaultState, ...opts };

But I keep getting the error "Expected '}' to match '{' and instead saw '...'". My .eslintrc is at https://gist.github.com/edspencer/1ef8d41a040548d8af85 (I essentially copy/pasted that from the one referenced in #14).

I believe I have the correct options set in .eslintrc (spread is set true everywhere), but the syntax continues to be flagged as an error. My npm package versions of the pertinent plugins are as follows:

"babel": "^6.3.26",
"babel-core": "^6.4.5",
"babel-eslint": "^5.0.0",
"babel-loader": "^6.2.1",
"babel-plugin-external-helpers-2": "^6.3.13",
"babel-plugin-syntax-export-extensions": "^6.3.13",
"babel-plugin-syntax-flow": "^6.3.13",
"babel-plugin-syntax-jsx": "^6.3.13",
"babel-plugin-transform-es2015-arrow-functions": "^6.4.0",
"babel-plugin-transform-es2015-block-scoping": "^6.4.0",
"babel-plugin-transform-es2015-classes": "^6.4.5",
"babel-plugin-transform-es2015-computed-properties": "^6.4.0",
"babel-plugin-transform-es2015-constants": "^6.1.4",
"babel-plugin-transform-es2015-destructuring": "^6.4.0",
"babel-plugin-transform-es2015-for-of": "^6.3.13",
"babel-plugin-transform-es2015-modules-commonjs": "^6.4.5",
"babel-plugin-transform-es2015-object-super": "^6.4.0",
"babel-plugin-transform-es2015-parameters": "^6.4.5",
"babel-plugin-transform-es2015-shorthand-properties": "^6.3.13",
"babel-plugin-transform-es2015-spread": "^6.4.0",
"babel-plugin-transform-es2015-template-literals": "^6.3.13",
"babel-plugin-transform-flow-strip-types": "^6.4.0",
"babel-plugin-transform-object-assign": "^6.3.13",
"babel-plugin-transform-object-rest-spread": "^6.3.13",
"babel-plugin-transform-react-constant-elements": "^6.4.0",
"babel-plugin-transform-react-display-name": "^6.4.0",
"babel-plugin-transform-react-inline-elements": "^6.4.0",
"babel-plugin-transform-react-jsx": "^6.4.0",
"babel-plugin-transform-remove-react-styl": "^1.0.5"

Any ideas what I'm doing wrong? The spread operator inside of JSX is recognized just fine - it's just when I use it outside of the JSX context that I'm getting this error reported. Also, the code itself is transpiled just fine by webpack and the resulting code runs correctly in the browser. For completeness, here's a fuller snippet of my function (which github refuses to recognize as code for some reason):

`
export default function pagination(model, opts = {}) {
const defaultState = {
isLoading: false,
loadedAt: null,
items: [],
total: 0,
page: 1,
perPage: 50,
sortColumn: 'created_at',
sortDirection: 'desc'
};

const modelState = { ...defaultState, ...opts };

//more codes down here

}
`

valid-jsdoc problem with class properties

Tell us about your environment

  • ESLint Version: 3.9.1
  • Node Version: 6.8.0
  • npm Version: 3.10.9

What parser (default, Babel-ESLint, etc.) are you using? [email protected]

Please show your full configuration:

{
	env: {
		'es6': true, // sets the "ecmaVersion" parser option to 6
	},
	parser: 'babel-eslint',
	plugins: [
		'babel'
	],
	rules: {
		'valid-jsdoc': 1
	}
}

What did you do? Please include the actual source code causing the issue.

/**
 * @class Whoops
 */
class Whoops {
	test = (wow) => {
		return wow;
	}
}

export default Whoops;

What did you expect to happen? No warning, test does not have a jsdoc tag

What actually happened? Please include the actual, raw output from ESLint.
1:1 warning Missing JSDoc for parameter 'wow' valid-jsdoc

If the method is changed to test(wow) { } then no warning is shown.

eslint reference: eslint/eslint#7555

Callable class constructors

There's a stage 1 proposal for callable class constructors that allows code like this:

import { initializeDate, ToDateString } from './date-implementation';

class Date {
  // `new Date()`
  constructor(...args) {
    initializeDate(super(), ...args);
  }

  // `Date()`
  call constructor() {
    return ToDateString(clockGetTime());
  }
}

And there's a babel transform for it.

But eslint doesn't seem to be able to handle it, even with this plugin. Am I configuring it wrong, or is this not supported?

Proposed rule: no-await-in-loop

I proposed this rule in an issue on eslint, but it was closed because they do not support experimental features.

This plugin says that it contains replacements to core ESLint rules. Would you relax that requirement and allow entirely new rules? If not, is there any place where a rule for ES7 would belong?

Function bind operator fails `no-invalid-this` rule

function fn() {
  return this.value;
}

const obj = {
  value: 42
};

obj::fn();

I can see why eslint proper doesn't support this usecase. Can eslint-plugin-babel provide a babel/no-invalid-this rule to support this usecase?

arrow-parens incompatible with flowtype

Not sure if this is the right repo for this issue, happy to go complain elsewhere :)

I'm running arrow-parens as-needed, but I'm also using flowtype. eslint complains that the parens are unnecessary on this type-annotated, single-parameter arrow function

const fn = (a: number) => {
  console.log(a);
};

I tried removing the parens, but that seems to be invalid syntax, as everything breaks at that point.

Have individual documentation pages for each rule

Hi all!

I'm a maintainer of eslint-rule-documentation which is a tool that associates ESLint plugin rule names to the url of the rule's documentation page. This allows other tools (Atom's ESLint linter, Atom's XO linter, eslint-find-rules) to link to it easily, in linting errors for instance. This allows users to find the documentation page for a rule and read it to better understand why the error has been reported or learn how to configure it more to their needs.

image

In this example, import/no-extraneous-dependencies is a link that redirects to https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md.

To provide a better experience to the users, eslint-rule-documentation should in my opinion link to an individual documentation page, where the rule is described in a bit of detail (reasoning, how it works, valid and invalid examples, when not to use it...). That is the case for ESLint core rules, and for many ESLint plugins. It is unfortunately not the case of this plugin, and would therefore request that you consider making this change. The standard way of doing things (advocated by the ESLint team) is to have individual markdown files located at docs/rules/<rulename>.md.

In the case of the rules copying and improving the behavior of core ESLint rules, I would recommend a simple file that would link to the original rule and describe why it should be used instead of the core ESLint rule.
For custom rules, something that looks like this or that would be awesome.

We have to manually add support for each ESLint plugin in eslint-rule-documentation to create links correctly (see what it looks like), and would prefer waiting to add support for this plugin until you have either refused, or agreed and implemented the change. I could provide help for this, but I would only do the grunt work, as I'm not accustomed to the rules to be able to explain the rationale for each.

Thank you for considering this, and of course, thank you all for your hard work on Babel and the plugin, they're awesome!

Release Question

I was just wondering when the latest release is coming out as the documentation in the README isn't what's available in the NPM module? This would be specifically around "array-bracket-spacing"

Installed as latest:

module.exports = {
  rules: {
    'generator-star-spacing': require('./rules/generator-star-spacing'),
    'new-cap': require('./rules/new-cap'),
    'object-curly-spacing': require('./rules/object-curly-spacing'),
    'object-shorthand': require('./rules/object-shorthand'),
    'arrow-parens': require('./rules/arrow-parens'),
    'no-await-in-loop': require('./rules/no-await-in-loop'),
  },
  rulesConfig: {
    'generator-star-spacing': 0,
    'new-cap': 0,
    'object-curly-spacing': 0,
    'object-shorthand': 0,
    'arrow-parens': 0,
    'no-await-in-loop': 0,
  }
};

Keep up the great work and thank you so much!

curly spacing and defaultMember and members on one line

The object-curly-spacing rule doesn't seem to apply to objects that are in the second half of a hybrid import statement like:

import React, {Component, PropTypes} from 'react';

Is there any way to get the plugin to mark these kinds of objects? Or do I have to put the members object on its own line?

Type declarations should be marked as hoisted at the top of the file

Would it be possible to update the "no-use-before-define" rule, so that the following code sample could pass: ?

type FooBar = Foo | Bar;
type Foo = { foo: string };
type Bar = { bar: number, baz: FooBar };

Since FooBar references Foo before it was declared, ESLint considers this an error. However type declarations are allowed to go in any order (for example so that recursive types can be supported), similar to functions.

What is needed to destructuring a function param?

eslint-plugin-babel version:

3.1.0

babel-eslint version:

5.0.0

eslint version:

2.1.0

I have following code.

class Foo {

    async print({a, b, c} = d) {

    }

    async spit() {
        await this.print({});
    }

    droll() {

    }
}

const foo = new Foo();

function zap() {

}

zap(foo);

Expected:

No errors

And got:

'd' is not defined.

What rules or ecmaFeatures should be enabled to get pass on this?

eslint 2.0.0 support

Right now the peerDependency for eslint is still in the 1.x.x version and npm complains:

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants eslint@>=1.0.0

What needs to be done to support the latest eslint?

Thanks for all the great work!

no async without await

I'm new to async await and find myself declaring functions as async but forgetting to await the promises inside of them (instead just calling let x = getData() or whatever. Would it make sense to have a rule that warned when you created an async function put didn't await inside that function?

I know you technically don't need await to use async, but might help some folks? Thoughts?

`array-bracket-spacing` and array destructuring in function parameters with flow types

test.js

/*eslint array-bracket-spacing: [2, "never"] */
function fnArray([a, b]: Array<any >): void {
  // nothing important
}

What versions I'm using

[email protected]
[email protected]

What I did

$eslint --parser babel-eslint test.js

What I expected

No errors

What actually happened

/tmp/test.js
  2:36  error  There should be no space before '>'  array-bracket-spacing

โœ– 1 problem (1 error, 0 warnings)

My Observations

The ArrayPattern node of the AST tree contains the type annotation.

function fnArray([a, b]: Array<any >): void {
//               ^-----------------^
//                ArrayPattern

The array-bracket-spacing rule checks the last and before last tokens of the AST node (ie. last is > an before last is any).

Since the between the before last token and last token their is a space and the expected is no space, an error is reported.

`babel/arrow-parens` is broken

This code breaks babel/arrow-parens rule:

const test = async (something) => {
    return something * 42;
};

test();

with this error

1:14  error  Expected parentheses around arrow function argument  babel/arrow-parens

My .eslintrc file: http://pastebin.com/zJW5KYTa

It should not throw this error.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.