Code Monkey home page Code Monkey logo

eslint-plugin-prettier's Introduction

eslint-plugin-prettier Build Status

Runs Prettier as an ESLint rule and reports differences as individual ESLint issues.

If your desired formatting does not match Prettier’s output, you should use a different tool such as prettier-eslint instead.

Please read Integrating with linters before installing.

TOC

Sample

error: Insert `,` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:22:25:
  20 | import {
  21 |   observeActiveEditorsDebounced,
> 22 |   editorChangesDebounced
     |                         ^
  23 | } from './debounced';;
  24 |
  25 | import {observableFromSubscribeFunction} from '../commons-node/event';


error: Delete `;` (prettier/prettier) at pkg/commons-atom/ActiveEditorRegistry.js:23:21:
  21 |   observeActiveEditorsDebounced,
  22 |   editorChangesDebounced
> 23 | } from './debounced';;
     |                     ^
  24 |
  25 | import {observableFromSubscribeFunction} from '../commons-node/event';
  26 | import {cacheWhileSubscribed} from '../commons-node/observable';


2 errors found.

./node_modules/.bin/eslint --format codeframe pkg/commons-atom/ActiveEditorRegistry.js (code from nuclide).

Installation

npm install --save-dev eslint-plugin-prettier eslint-config-prettier
npm install --save-dev --save-exact prettier

eslint-plugin-prettier does not install Prettier or ESLint for you. You must install these yourself.

This plugin works best if you disable all other ESLint rules relating to code formatting, and only enable rules that detect potential bugs. If another active ESLint rule disagrees with prettier about how code should be formatted, it will be impossible to avoid lint errors. Our recommended configuration automatically enables eslint-config-prettier to disable all formatting-related ESLint rules.

Configuration (legacy: .eslintrc*)

For legacy configuration, this plugin ships with a plugin:prettier/recommended config that sets up both eslint-plugin-prettier and eslint-config-prettier in one go.

Add plugin:prettier/recommended as the last item in the extends array in your .eslintrc* config file, so that eslint-config-prettier has the opportunity to override other configs:

{
  "extends": ["plugin:prettier/recommended"]
}

This will:

  • Enable the prettier/prettier rule.
  • Disable the arrow-body-style and prefer-arrow-callback rules which are problematic with this plugin - see the below for why.
  • Enable the eslint-config-prettier config which will turn off ESLint rules that conflict with Prettier.

Configuration (new: eslint.config.js)

For flat configuration, this plugin ships with an eslint-plugin-prettier/recommended config that sets up both eslint-plugin-prettier and eslint-config-prettier in one go.

Import eslint-plugin-prettier/recommended and add it as the last item in the configuration array in your eslint.config.js file so that eslint-config-prettier has the opportunity to override other configs:

const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');

module.exports = [
  // Any other config imports go at the top
  eslintPluginPrettierRecommended,
];

This will:

  • Enable the prettier/prettier rule.
  • Disable the arrow-body-style and prefer-arrow-callback rules which are problematic with this plugin - see the below for why.
  • Enable the eslint-config-prettier config which will turn off ESLint rules that conflict with Prettier.

Svelte support

We recommend to use eslint-plugin-svelte instead of eslint-plugin-svelte3 because eslint-plugin-svelte has a correct eslint-svelte-parser instead of hacking.

When use with eslint-plugin-svelte3, eslint-plugin-prettier will just ignore the text passed by eslint-plugin-svelte3, because the text has been modified.

If you still decide to use eslint-plugin-svelte3, you'll need to run prettier --write *.svelte manually.

arrow-body-style and prefer-arrow-callback issue

If you use arrow-body-style or prefer-arrow-callback together with the prettier/prettier rule from this plugin, you can in some cases end up with invalid code due to a bug in ESLint’s autofix – see issue #65.

For this reason, it’s recommended to turn off these rules. The plugin:prettier/recommended config does that for you.

You can still use these rules together with this plugin if you want, because the bug does not occur all the time. But if you do, you need to keep in mind that you might end up with invalid code, where you manually have to insert a missing closing parenthesis to get going again.

If you’re fixing large of amounts of previously unformatted code, consider temporarily disabling the prettier/prettier rule and running eslint --fix and prettier --write separately.

Options

Note: While it is possible to pass options to Prettier via your ESLint configuration file, it is not recommended because editor extensions such as prettier-atom and prettier-vscode will read .prettierrc, but won't read settings from ESLint, which can lead to an inconsistent experience.

  • The first option:

    • An object representing options that will be passed into prettier. Example:

      {
        "prettier/prettier": [
          "error",
          {
            "singleQuote": true,
            "parser": "flow"
          }
        ]
      }

      NB: This option will merge and override any config set with .prettierrc files

  • The second option:

    • An object with the following options

      • usePrettierrc: Enables loading of the Prettier configuration file, (default: true). May be useful if you are using multiple tools that conflict with each other, or do not wish to mix your ESLint settings with your Prettier configuration. And also, it is possible to run prettier without loading the prettierrc config file via the CLI's --no-config option or through the API by calling prettier.format() without passing through the options generated by calling resolveConfig.

        {
          "prettier/prettier": [
            "error",
            {},
            {
              "usePrettierrc": false
            }
          ]
        }
      • fileInfoOptions: Options that are passed to prettier.getFileInfo to decide whether a file needs to be formatted. Can be used for example to opt-out from ignoring files located in node_modules directories.

        {
          "prettier/prettier": [
            "error",
            {},
            {
              "fileInfoOptions": {
                "withNodeModules": true
              }
            }
          ]
        }
  • The rule is auto fixable -- if you run eslint with the --fix flag, your code will be formatted according to prettier style.


Sponsors

@prettier/plugin-eslint eslint-config-prettier eslint-plugin-prettier prettier-eslint prettier-eslint-cli
@prettier/plugin-eslint Open Collective sponsors eslint-config-prettier Open Collective backers eslint-plugin-prettier Open Collective backers prettier-eslint Open Collective sponsors prettier-eslint-cli Open Collective backers

Backers

@prettier/plugin-eslint eslint-config-prettier eslint-plugin-prettier prettier-eslint prettier-eslint-cli
@prettier/plugin-eslint Open Collective backers eslint-config-prettier Open Collective backers eslint-plugin-prettier Open Collective backers prettier-eslint Open Collective backers prettier-eslint-cli Open Collective backers

Contributing

See CONTRIBUTING.md

Changelog

Detailed changes for each release are documented in CHANGELOG.md.

License

MIT

eslint-plugin-prettier's People

Contributors

arcanemagus avatar auvred avatar azz avatar bpscott avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar filiptammergard avatar fisker avatar github-actions[bot] avatar ikatyang avatar josephfrazier avatar jounqin avatar kombucha avatar kripod avatar krist7599555 avatar lencioni avatar logicer16 avatar louim avatar lydell avatar merceyz avatar michaeldeboey avatar neighborhood999 avatar not-an-aardvark avatar rootulp avatar schweinepriester avatar sebjambor avatar simenb avatar yyx990803 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  avatar

eslint-plugin-prettier's Issues

prettier config ignored by plugin (even with latest version of prettier)

Related to #59, the prettier block in package.json is ignored by this plugin (and additional ignored for overrides).

The only way you can use eslint-plugin-prettier with a custom prettier config is by explicitly defining that same config in the plugin usage:

    "rules": {
      "prettier/prettier": [
        "error",
        {
          "singleQuote": true,
          "bracketSpacing": true,
          "trailingComma": "none"
        }
      ],

[Linter] Error running ESLint Error: require(...).getLocationFromRangeIndex is not a function(…)

ESLint is failing to run for me with eslint-plugin-prettier rules activated (i.e. with "rules": { "prettier/prettier": "error" } set).

This is the stacktrace from atom:

image

As it says in the stacktrace, the error comes from this file on line 30 where it calls require('eslint/lib/ast-utils').getLocationFromRangeIndex(...).

Upon inspection of eslint/lib/ast-utils I see that the function no longer exists. The function was removed in this commit.

disable missing space before function parentheses

Hi :)
First of all, thank u for this plugin.

Problem
For this piece of code:

async function main({ host = HOST, port = PORT } = {}) { 
...

I get the following warning on my project:

screenshot_2017-08-16_17-28-08

When I add a space according to the warning then I get an error by prettier that says remove the space. When I remove your plugin it doesn't warn me anymore but I have to add a space after the function name.

How can I fix that? Are there any options that I can pass to disable this?

Environment
I'm using

  • Atom 1.19
  • Node 8
  • Linux OS

.eslintrc.json

{
  "parser" : "babel-eslint",
  "extends": [
    "prettier"
  ],
  "plugins": [
    "prettier"
  ],
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module"
  },
  "env": {
    "es6": true,
    "node": true
  },
  "rules": {
    "curly": ["error", "all"],
    "max-len": ["error", {"code": 80, "ignoreUrls": true}],
    "no-confusing-arrow": "error",
    "no-tabs": "error",
    "quotes": ["error", "backtick"],
    "space-in-parens": 2,
    "space-before-function-paren": 0,
    "prettier/prettier": ["error",
      {
      "semi": false,
      "singleQuote": true
      }
    ]
  }
}

package.json

...
"devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2017": "^6.24.1",
    "eslint": "^4.4.1",
    "eslint-config-prettier": "^2.3.0",
    "eslint-plugin-prettier": "^2.2.0",
    "prettier": "^1.5.3"
  }
...

`plugin:prettier/recommended` doesn't include `prettier/react`

The plugin:prettier/recommended doesn't seem to include the prettier/react component. Is this my design or by mistake?

I would expect plugin:prettier/recommended to take care of all the rule removal that it could possibly want to change.

"eslint": "^4.0.0",
"prettier": "^1.9.2",
"eslint-plugin-prettier": "^2.4.0",

.eslintrc

{
  "parser": "babel-eslint",
  "extends": [
    "eslint-config-airbnb",
    "plugin:prettier/recommended"
  ]
}

What source code are you linting?

const userMenuItems = []
  .concat(
    user ? (
      <UserDetails
        key="userDetails"
        email={user.email_address}
        name={`${user.first_name} ${user.last_name}`}
      />
    ) : null,
    <HorizontalLine key="hr1" />
  );

The react indent rule seems to conflict with prettier and isn't being taken out by the recommended configs.

When 6 spaces:
<HorizontalLine key="hr1" />
Insert ·· prettier/prettier

When 8 spaces:
<HorizontalLine key="hr1" />
Expected indentation of 6 space characters but found 8 react/jsx-indent

Possible to enable for fix only?

Is it possible to enable this only during a --fix and not during a regular run (like in an editor?)

I'd rather not have the noise of auto-fixable errors showing up in my editor since they'd be fixed when I save any way.

Thanks!

Export a "recommended" configuration

Usually when I set up a project with Prettier I use both eslint-{plugin,config}-prettier.

---
plugins:
- prettier # eslint-plugin-prettier
extends:
- prettier # eslint-config-prettier
rules:
  prettier/prettier: error # eslint-plugin-prettier

What would be great is if this module exported a "recommended" configuration that did this for me:

---
extends:
- plugin:prettier/recommended

Effectively:

module.exports.configs = {
  recommended: {
    extends: ['prettier'],
    plugins: ['prettier'],
    rules: {
      'prettier/prettier': 'error'
    },
  }
}

Would such an addition be welcome?

Definition for rule 'prettier/prettier' was not found prettier/prettier

Hi,

We're having trouble integrating prettier with eslint. We used eslint-plugin-prettier together with eslint-configure-prettier. Here's the content of the package.json that we use

{
  ...
  "scripts": {
    ...,
    "lint": "./node_modules/.bin/eslint .",
   ...
  },
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...,
    "eslint": "^3.17.1",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-config-loopback": "^4.0.0",
    "eslint-config-prettier": "^2.0.0",
    "eslint-import-resolver-babel-module": "^3.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-prettier": "^2.0.1",
    ...,
    "prettier": "^1.3.1",
    "prettier-eslint": "^6.2.0",
    "prettier-eslint-cli": "^3.4.3",
    ...
  },
  "repository": {
    "type": "",
    "url": ""
  },
 ...
}

Here is our .eslintrc config file

{
  "parser": "babel-eslint",
  "extends": [
    "airbnb/base",
    "prettier"
  ],
  "parserOptions": {
    "ecmaVersion": 8,
    "sourceType": "module"
  },
  "env": {
    "es6": true,
    "node": true
  },
  "rules": {
    "prettier/prettier": "error",
    "arrow-parens": [
      "error",
      "always"
    ],
    "arrow-body-style": [
      2,
      "as-needed"
    ],
    "comma-dangle": [
      2,
      "always-multiline"
    ],
    "import/imports-first": 0,
    "import/newline-after-import": 0,
    "import/no-dynamic-require": 0,
    "import/no-extraneous-dependencies": 0,
    "import/no-named-as-default": 0,
    "import/prefer-default-export": 0,
    "indent": [
      2,
      2,
      {
        "SwitchCase": 1
      }
    ],
    "linebreak-style": [
      2,
      "unix"
    ],
    "new-cap": [
      2,
      {
        "properties": false
      }
    ],
    "no-unused-vars": [
      2,
      {
        "vars": "all",
        "args": "after-used"
      }
    ],
    "no-use-before-define": [
      2
    ],
    "no-trailing-spaces": [
      2
    ],
    "quotes": [
      2,
      "single"
    ],
    "semi": [
      2,
      "always"
    ],
    "wrap-iife": [
      2,
      "outside"
    ],
    "strict": [
      2,
      "global"
    ],
    "brace-style": 2,
    "block-spacing": [
      2,
      "always"
    ],
    "keyword-spacing": [2, {"before": true, "after": true, "overrides": {}}],
    "space-before-blocks": 2,
    "space-before-function-paren": [2, {"anonymous": "always", "named": "never"}],
    "comma-spacing": [2, {"before": false, "after": true}],
    "comma-style": [2, "last"],
    "no-lonely-if": 2,
    "array-bracket-spacing": [2, "never"],
    "no-spaced-func": [2],
    "space-in-parens": [2, "never"],
    "space-infix-ops": 2
  },
  "settings": {
    "import/resolver": {
      "babel-module": {}
    }
  },
  "globals": {
    "after": true,
    "afterEach": true,
    "before": true,
    "beforeEach": true,
    "describe": true,
    "it": true
  }
}

Everytime we start linting, it says that Definition for rule 'prettier/prettier' was not found prettier/prettier. Do we miss some dependencies for it? :)

error Delete

i get
screen shot 2017-08-13 at 4 48 53 pm

.eslintrc

{ "extends": ["airbnb", "prettier"], "env": { "browser": true, "node": true }, "globals": { "test": true, "expect": true, "describe": true, "FB": true }, "parser": "babel-eslint", "plugins": [ "react", "prettier" ], "parserOptions": { "ecmaVersion": 5, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "rules": { "prettier/prettier": ["error", { "singleQuote": true }], "react/jsx-no-bind": 1, "strict": 2, "max-len": ["error", 250], "space-before-function-paren": ["error", { "anonymous": "always" }], "comma-dangle": [1, "never"], "import/no-extraneous-dependencies": ["error", { "devDependencies": true }], "react/forbid-prop-types": [0], "react/jsx-filename-extension": [1, { "extensions": [".js",".jsx"] }], "no-param-reassign": ["error", { "props": false }], "quotes": [2, "single"] } }

.babelrc
{ "presets": [ "es2015", "react", "stage-3", "stage-2" ], "plugins": [ "transform-class-properties", "transform-object-assign", "transform-flow-strip-types", "syntax-dynamic-import" ], "env": { "test": { "plugins": [ "istanbul" ] } } }

.editorConfig
`root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
in_empty_tag = true
`
i use webstorm file watcher

--single-quote --write $FilePath$

With eslint fix mode, and using eslint-config-prettier, I still get lint errors every time.

I was hoping that running fix mode of eslint would cause the prettier plugin to fix stuff, and there would be no more prettier-related lint errors, but that isn't the case. Maybe eslint-config-prettier needs an update?

Here's a branch (in the wrong repo) that you can reproduce from: https://github.com/trusktr/gulp-eslint/tree/issue-204

Just clone that repo and checkout that issue-204 branch, npm i, then run ./node_modules/.bin/gulp lint a few times, and each time the output will continue to show prettier-related errors.

I thought there would be no prettier errors at least the second round if it fixed everything the first round.

"error Delete `⏎` prettier/prettier" in .vue files

I get a "Delete prettier/prettier" error within the script tags of my .vue files.

Delete ⏎  prettier/prettier

I'm using VS Code with ESLint.
When I save the .vue file, it auto-'fixes' the file using prettier, only not in the preferred way.

Fixed: Delete ⏎  prettier/prettier

There might be something wrong with my .eslintrc.json file, but I'm not sure what it is.

.eslintrc.json

{
  "root": true,
  "parser": "babel-eslint",
  "env": {
    "browser": true
  },
  "extends": [
    "standard",
    "eslint:recommended",
    "prettier"
  ],
  "plugins": [
    "html",
    "prettier"
  ],
  "rules": {
    "prettier/prettier": [
      "error",
      {
        "singleQuote": true
      }
    ]
  }
}

.babelrc

{
  "presets": [
    "env",
    "stage-2"
  ]
}

.vscode/settings.json

{
  "eslint.autoFixOnSave": true,
  "eslint.validate": [
    "javascript",
    {
      "language": "vue",
      "autoFix": true
    }
  ]
}

`eslint --fix` does not work properly when used with `prefer-arrow-callback`

What version of eslint are you using?

4.14.0.

What version of prettier are you using?

1.9.2.

What version of eslint-plugin-prettier are you using?

2.4.0.

Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)

.eslintrc.yaml:

extends:
  - plugin:prettier/recommended

parserOptions:
  ecmaVersion: 6

rules:
  prefer-arrow-callback: "error"

What source code are you linting?

function func(arg) {
  return Array.isArray(arg.param) && foo.bar.filter(function(baz) {
    return baz.code === 42;
  }).length > 0;
}

What did you expect to happen?

When applying eslint --fix I would expect it to generate valid code.

What actually happened?

It generates invalid code:

function func(arg) {
  return (
    Array.isArray(arg.param) &&
    foo.bar.filter((baz) => {
    return baz.code === 42;
  }).length > 0;
}

I managed to create this minimal reproducible environment, which can be found here.

When I run eslint --fix index.js, it generates invalid code. But if I remove the plugin from the ESLint configuration, run eslint --fix index.js and then run prettier --write index.js it will generate the expected output.

Relax pragma rules

At the moment the pragma has to be the first line and in the /** @yourPragma */ format. If it's used in a file with Flow it means you have to remember to put the Prettier one first.

This isn't a huge hassle but it caused me a few minutes of confusion as I thought I had things set up wrong. It would be nice if this plugin's pragma were more like Flow's and could be in either // @yourPragma or /** @yourPragma */ format and be anywhere in the file.

linter semicolon errors

I added the plugin to my .eslintrc
screen shot 2017-03-10 at 16 28 53 2

But I still get:
screen shot 2017-03-10 at 16 29 22 2

Note that I get the error when I run eslint . as well.

Am I missing something? 🤔

autoFixOnSave alternates between correct and wrong indentation

What version of eslint are you using? 4.11.0
What version of prettier are you using? 1.8.2
What version of eslint-plugin-prettier are you using? 2.3.1

Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)

Global settings VSCode:

  "eslint.autoFixOnSave": true,

.eslintrc.json

{
  "extends": "prettier",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2017
  },
  "env": {
    "es6": true,
    "node": true
  },
  "plugins": [
    "prettier"
  ],
  "rules": {
    "prettier/prettier": [
      "error",
      {
        "semi": false,
        "printWidth": 120
      }
    ]
  }
}

I have quite strange error. I set eslint.autoFixOnSave to true. When I save a file once it formats my code successfully:

image

When I save it again it messes up the indentation.

image

When I save a 3rd time it fixes the indentation again as in screenshot 1 and so on.

How can this happen?
This is my .eslintrc.json:

{
  "extends": "prettier",
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 2017
  },
  "env": {
    "es6": true,
    "node": true
  },
  "plugins": [
    "prettier"
  ],
  "rules": {
    "prettier/prettier": [
      "error",
      {
        "semi": false,
        "printWidth": 120
      }
    ]
  }
}

Edit: I recorded a video with the strange behaviour:

eslint-problem

Transition plan for new `requirePragma` in prettier core

I just got the pragma functionality merged into prettier itself at prettier/prettier#2772. It is very similar to the functionality implemented here, only:

  • Now editors can use their autoformat functionality and follow the same rules for applying based on the pragma as other tools
  • The name of the pragma is fixed to either @prettier or @format. There's a bit of discussion in that PR behind this reasoning.

How should we manage the transition from eslint-plugin-prettier's implementation of pragmas to the new one in core? Off the top of my head it makes sense to no longer use the third option for this plugin, and instead either rely on a .prettierrc or instruct users to pass along requirePragma in the second options argument of this plugin.

Thanks! cc @asuarez

inter] Error running ESLint Error: require(...).getLocationFromRangeIndex is not a function(…)

Hi there!

I have installed this plugin as instructed on the repo. I am using latest version of Atom with latest version of linter-eslint, and also latest eslint installed to my project. Also latest prettier.

For some reason when I save I get the error in the title of this issue. Not sure where to start here :) The error goes away when I remove the prettier rule from the rules map.

overrides are ignored

What version of eslint are you using?
4.10.0
What version of prettier are you using?
1.8.1
What version of eslint-plugin-prettier are you using?
2.3.1
Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)
My eslint config

module.exports = {
	extends: ['myCompany', 'prettier'],
	plugins: ['prettier'],
	rules: {
		'prettier/prettier': [
			'error',
			{
				printWidth: 100,
				tabWidth: 4,
				useTabs: true,
				semi: true,
				singleQuote: true,
				trailingComma: 'es5',
				bracketSpacing: true,
				jsxBracketSameLine: false,
				rangeStart: 0,
				rangeEnd: Infinity,
				proseWrap: true,
				overrides: [
					{
						files: ['*.scss', '*.css'],
						options: {
							useTabs: false,
							tabWidth: 2,
						},
					},
					{
						files: ['*.json'],
						options: {
							useTabs: false,
							tabWidth: 2,
						},
					},
					{
						files: ['*.md'],
						options: {
							useTabs: false,
							tabWidth: 4,
						},
					},
				],
			},
		],
	},
};

What source code are you linting?
JavaScript, CSS/SCSS, Markdown, JSON
What did you expect to happen?
A valid eslint+prettier config
What actually happened?

The eslint output

● Validation Warning:

  Unknown option "proseWrap" with value true was found.
  This is probably a typing mistake. Fixing it will remove this message.

● Validation Warning:

  Unknown option "overrides" with value [{"files": ["*.scss", "*.css"], "options": {"tabWidth": 2, "useTabs": false}}, {"files": ["*.json"], "options": {"tabWidth": 2, "useTabs": false}},{"files": ["*.md"], "options": {"tabWidth": 4, "useTabs": false}}] was found.
  This is probably a typing mistake. Fixing it will remove this message.

● Validation Warning:

  Unknown option "proseWrap" with value true was found.
  This is probably a typing mistake. Fixing it will remove this message.

● Validation Warning:

  Unknown option "overrides" with value [{"files": ["*.scss", "*.css"], "options": {"tabWidth": 2, "useTabs": false}}, {"files": ["*.json"], "options": {"tabWidth": 2, "useTabs": false}},{"files": ["*.md"], "options": {"tabWidth": 4, "useTabs": false}}] was found.
  This is probably a typing mistake. Fixing it will remove this message.

How to use it with grunt?

Trying like this with https://github.com/sindresorhus/grunt-eslint

		eslint: {
			options: {
				format: require('eslint-plugin-prettier')
			},
				target: ['app/styles/**/*.scss']
		},

But it's not working

Running "eslint:target" (eslint) task
Warning: Could not find formatter [object Object] Use --force to continue.

Aborted due to warnings.

Non-JS support (Specifically Markdown)

Prettier 1.8 has Markdown support. It also formats code blocks with Markdown.

Would it make sense to support Markdown in this plugin using a processor? Perhaps it could even work alongside eslint-plugin-markdown?

I haven't tried yet, but I imagine eslint-plugin-markdown will already work with this plugin to provide errors and fixes for the embedded code blocks, but maybe fixes for the Markdown itself could be supported too?

Support prettier v1.6.0 config

Prettier v1.6.0 is out, and it implements cosmiconfig for options.

This plugin currently requires prettier config to be set within ESLint config. It would be awesome to deprecate this and let prettier derive the config itself.

line-by-line error reporting

Hey @not-an-aardvark, thanks a ton for working on this plugin, this turned out to be the way most people are integrating prettier inside of their stack :)

We've been working on a different implementation at Facebook. At first we started it to support annotating files with @format (like @flow) and only running the lint rule on them, for a migration path.

In the process, we added a super nice feature where instead of reporting a single eslint message at the top of the file, we diff the file and the prettier output and give suggestions for each line that needs to be changed. When you have an editor integration, it shows it inline like any other lint rule, which is really nice.

https://github.com/zertosh/eslint-plugin-prettify

I was wondering if we could figure out a way to get those two projects to converge, so that people using prettier have the best possible integration :)

Thanks!

.prettierc overrides are ignored

It seems the plugin ignores prettier's overrides options. E.g. the following .prettierc fails for the directory build_tools:

{
  "trailingComma": "all",
  "overrides": [
    {
      "files": "build_tools/*.js",
      "options": {
        "trailingComma": "es5"
      }
    }
  ]
}

Use `formatAST`.

In the code there is this comment:

// This isn't really very performant (prettier needs to reparse the text).
// However, I don't think it's possible to run `prettier` on an ESTree AST.

We do provide a formatAST function for passing in an AST. What you can't do is run both eslint --fix and prettier.format in the same pass because they both make modifications to text, not AST, so they both output text (I think eslint might be able to output some generic structure, but we'd have to re-parse it anyway).

I'm not too familiar with eslint plugins, but if you're just running eslint and you get an AST you should be able to use it.

Conflict --config argument with Webpack triggers validation warning.

I don't think this is a bug for eslint-plugin-prettier, but one recent PR gives Prettier a chance to load its configure file even in API mode introduce conflict with Webpack at least.

Since 1.6.0 Prettier now pickup '--config' arg from the command line to load its configuration, but it didn't distinguish who was the arg for, so if you set it up with webpack, eslint-loader and eslint-plugin-prettier and running command like

webpack --config webpack.dev.js

could have webpack.dev.js file been pick up by prettier as configuration thus resulting Validation Warning like this:

● Validation Warning:

Unknown option "devtool" with value "#source-map" was found.
This is probably a typing mistake. Fixing it will remove this message.

The reason I rise it here is that given the 'bridge' nature of eslint-plugin-prettier that using prettier in API mode, perhaps we could have flag controls this "loads config file by its self like it did in command mode" behaviour, I'm currently holding at version 2.2.0 to avoid this.

Just my 2 cents, not sure if it's duplicated, Please feel free to correct me.

Replace ' ' with Return Symbol (⏎······'code',⏎)

What version of eslint are you using?
4.10

What version of prettier are you using?
1.8.2

What version of eslint-plugin-prettier are you using?
2.3.1

Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)

{
  "extends": ["airbnb", "prettier"],
  "plugins": ["prettier"],
  "parserOptions": {
    "ecmaVersion": 2016,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "env": {
    "es6": true,
    "browser": true,
    "node": true
  },
  "globals": {
    "_": true
  },
  "rules": {
    "no-console": 0,
    "prefer-template": 0,
    "no-underscore-dangle": 0,
    "jsx-a11y/anchor-is-valid": [
      "error",
      {
        "components": ["Link"],
        "specialLink": ["to", "hrefLeft", "hrefRight"],
        "aspects": ["noHref", "invalidHref", "preferButton"]
      }
    ],
    "prettier/prettier": ["error", { "singleQuote": true }]
  }
}

What source code are you linting?
self.sup.addEventListener('change-background', self.changeBackground);

What did you expect to happen?
Did not expect an error because my sublime Jsprettier extension does not make any changes to the written code. I tried the code on prettier.io website and that too didn't change the formatting.

What actually happened?
Error :
Replace 'change-background',·self.changeBackground with ⏎······'change-background',⏎······self.changeBackground⏎····

On running eslint --fix it fixes the code to

self.el.sceneEl.addEventListener(
  'change-background',
  self.changeBackground
);

But on formatting the file in sublime by saving, it does not format in the above shown manner, which results in the error.

I want to remove this error and use the original style of code I have written, but not finding a rule to disable this.

Thanks

Installation problem

npm i eslint-plugin-prettier -D
npm ERR! node v6.11.3
npm ERR! npm  v3.10.10
npm ERR! code ETARGET

npm ERR! notarget No compatible version found: fast-diff@^1.1.1
npm ERR! notarget Valid install targets:
npm ERR! notarget 1.1.0, 1.0.1, 1.0.0

Support ESLint 4

ESLint is now available in version 4, here are the breaking changes for plugin developers.

I don't know if there is actually something to do here aside from bumping the peerDependency semver :)

SCSS prettifying does not seems to use the correct parser - Parsing error: Unexpected token

I wanted to use it for scss only but getting these errors in almost all scss files. I'm using it with this config #28 (comment)

/Users/jitendravyas/app-v3/app/styles/components/_graph.scss
  1:1  error  Parsing error: Unexpected token

/Users/jitendravyas/app-v3/app/styles/components/_headings.scss
  2:1  error  Parsing error: Unexpected token

/Users/jitendravyas/app-v3/app/styles/components/_heatmap-thumbnail.scss
  6:1  error  Parsing error: Unexpected token

/Users/jitendravyas/app-v3/app/styles/components/_identifier-icons.scss
  11:1  error  Parsing error: Unexpected token

/Users/jitendravyas/app-v3/app/styles/components/_islands.scss
  4:1  error  Parsing error: Unexpected token

/Users/jitendravyas/app-v3/app/styles/components/_loaders.scss
  1:1  error  Parsing error: Unexpected token

Prettier trailingComma setting is now a string

The trailingComma option has been changed to the following possible values:

  // Controls the printing of trailing commas wherever possible. Valid options:
  // "none" - No trailing commas
  // "es5"  - Trailing commas where valid in ES5 (objects, arrays, etc)
  // "all"  - Trailing commas wherever possible (function arguments)
  //
  // NOTE: Above is only available in 0.19.0 and above. Previously this was
  // a boolean argument.
  trailingComma: "none",

https://github.com/prettier/prettier#api

But this plugin still enforces it to be a boolean.
screen shot 2017-02-22 at 16 50 38

Clearer documentation about setting node environment for sublime to what prettier was installed with

After installing prettier and following the instructions I was hitting this issue:

/Users/ml/.nvm/versions/node/v4.4.4/lib/node_modules/prettier/bin/prettier.js:5
const fs = require("fs");
^^^^^
SyntaxError: Use of const in strict mode.
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:935:3

I wasn't sure what the problem was. After some digging, I found that I needed to have my node environment for sublime (for me project specific) as prettier was installed with. Setting this in my .sublime-project file solved it for me:

  "settings": {
    "js_prettier": {
      "prettier_cli_path": "/Users/ml/.nvm/versions/node/v4.4.4/bin/prettier",
      "node_path": "/Users/ml/.nvm/versions/node/v4.4.4/bin/node"
    }
  }

This was not super obvious to me. Could this be documented clearer somewhere?

Related issue: prettier/prettier#99 (comment)

Support for JSON files, coming to Prettier 1.5

Hi

is it possible to use prettier via eslint-plugin-prettier for linting and formatting JSON files in the project?

It's nice to have specified linting and formatting glob patterns on one single place in the eslint run script. Now, when prettier 1.5 has builtin support for JSON files, would be great to add those files to eslint too, but eslint is unable to parse JSON files at all.

There is a plugin for linting JSON files called elist-plugin-json but this is completely other beast, it only checks if JSON is valid. But it's proof that it is generally possible for plugins to add JSON parser to ESlint ecosystem.

Bad formatting closing script-tag in vue-files

What version of eslint are you using?
"eslint": "4.15.0",

What version of prettier are you using?
"prettier": "1.10.2",

What version of eslint-plugin-prettier are you using?
"eslint-plugin-prettier": "2.5.0",

Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)

const resolve = require('path').resolve;

module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint'
  },
  env: {
    browser: true,
    node: true,
    jest: true
  },
  extends: [
    'standard',
    'prettier',
    'plugin:vue/base',
    'plugin:vue/essential',
    'plugin:vue/strongly-recommended',
    'plugin:vue/recommended'
  ],
  plugins: ['html', 'variables', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
    'import/no-unresolved': 'error',
    'variables/only-ascii-variables': 'error'
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: {
          resolve: {
            alias: {
              '~': __dirname
            }
          }
        }
      }
    }
  }
};
"prettier": {
    "printWidth": 120,
    "tabWidth": 2,
    "useTabs": false,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true
  },

What source code are you linting?
https://pastebin.com/Hzik4pNs

What did you expect to happen?
Formatting correct

What actually happened?
After updating eslint-plugin-prettier from 2.4.0 to 2.5.0 and run eslint --fix --ext .js,.vue --ignore-path .gitignore .
image

Fails with eslint v3.12.0

Neither getLocationFromRangeIndex or getLocFromIndex. There should probably be a better warning message like this library requires a dep greater than 3.12.0.

prefer-arrow-callback fix conflicting with prettier fix

Edit by @lydell: TL;DR We recommend turning off these rules for the time being:

{
  "rules": {
    "arrow-body-style": "off",
    "prefer-arrow-callback": "off"
  }
}

What version of eslint are you using?
v4.9.0

What version of prettier are you using?
v1.7.4

What version of eslint-plugin-prettier are you using?
v2.3.1

Please paste any applicable config files that you're using (e.g. .prettierrc or .eslintrc files)
https://github.com/ismail-syed/prettier-eslint-config-invalid-code

What source code are you linting?

function foo() {
  return isTrue && [0,1,2].map(function(num) {
    return num * 2;
  });
}

What did you expect to happen?
The code above should be formatted as per prettiers config and also should adhere to that prefer-arrow-callback fix

What actually happened?
Invalid code was generated, closing parenthesis is missing on the return statement.

function foo() {
  return (
    isTrue &&
    [0, 1, 2].map((num) => {
    return num * 2;
  });
}

Is the underlying issue from the prefer-arrow-callback fixer or the prettier plugin fixer?

useTabs oddity...

I installed this plugin to play with prettier, and set the useTabs true and ran a fix... my file was indented with tabs (expected) but the prettier rule shows errors to replace tabs with spaces...

Removes trailing newline

Using this plugin give me errors such as error Delete '⏎' prettier/prettier when using eslint. It is not a problem with prettier because running prettier directly does not remove them. I am using v2.1.1 of the plugin.

Expose report-related APIs in another package

Currently, all the APIs are not exposed, so that it can't be reused by other linter-plugin, e.g. tslint-plugin-prettier (currently just copy-paste implementations from this repo).

It'd be better to expose report-related APIs in another package (since this repo has peerDeps for eslint), so that it can be reused in different linter plugin to have consistent behavior.

Suggested API

export declare function showInvisibles(str: string): string;
export declare function reportDifferences(source: string, formatted: string, reporters: Reporters);

export interface Reporters {
  reportInsert: (offset: number, text: string, message: string) => void;
  reportDelete: (offset: number, text: string, message: string) => void;
  reportReplace: (offset: number, deleteText: string, insertText: string, message: string) => void;
}

Improve report location calculations

Given this example:

import expect from '../../../../testUtils/unexpectedReact';
import React from 'react';
import FormattedSize from '../FormattedSize';

it('should render 123 bytes as 0.1KB', () => expect(
    <FormattedSize size={123} />,
    'to render as',
    <span>0.1 KB</span>
));

it('should render 1241240 bytes as 1.2MB', () => expect(
    <FormattedSize size={1241240} />,
    'to render as',
    <span>1.2 MB</span>
));

Prettier wants it formatted as:

import expect from '../../../../testUtils/unexpectedReact';
import React from 'react';
import FormattedSize from '../FormattedSize';

it('should render 123 bytes as 0.1KB', () =>
    expect(<FormattedSize size={123} />, 'to render as', <span>0.1 KB</span>));

it('should render 1241240 bytes as 1.2MB', () =>
    expect(
        <FormattedSize size={1241240} />,
        'to render as',
        <span>1.2 MB</span>
    ));

But running eslint gives me the following report:

$ ./node_modules/.bin/eslint src/common/components/FormattedSize/__tests__/FormattedSize-test.js 

./src/common/components/FormattedSize/__tests__/FormattedSize-test.js
  5:45  error  Follow `prettier` formatting (expected '\n' but found ' ')  prettier/prettier

I expected an error to be reported on both line 5 and 11, not just line 5. If I proceed to actually run prettier, both are fixed up as expected.

Other rules continue to work as expected, but this plugin and it's rule will only report the first problem.

Delete `.(` warning in React Stateless Component

Hi,

Thanks for this plugin. Prettier is keep complaining about ( and ) around JSX on a stateless component. Is it a bug or are there any rule to disable this warning?

const App = ({ session }) => (
   <div>Hello!</div>
);

Make extendable preset

Wouldn't it make sense to have this as a preset instead of a plugin? This way you would make rules overwritable and hence have it compatible with prettier-eslint.

E.g.

{
  "extends": "prettier",
  "rules": {
    "quotes": ["error", "single"],
   }
}

instead of

{
    "plugins": [
        "prettier"
    ],
    "rules": {
        "prettier/prettier": ["error", {"singleQuote": true}]
    }
}

--fix not working for some rules?

I'm using the plugin with ESLint 4, in version 2.1.2, when I run the command I get this:

$ eslint rules --fix
/rules/best-practices.js
   8:9  error  Replace `"complexity"` with `complexity`  prettier/prettier
  10:9  error  Replace `"curly"` with `curly`            prettier/prettier
  14:9  error  Replace `"eqeqeq"` with `eqeqeq`          prettier/prettier
  65:9  error  Replace `"radix"` with `radix`            prettier/prettier
  68:9  error  Replace `"yoda"` with `yoda`              prettier/prettier

✖ 9 problems (9 errors, 0 warnings)
  9 errors, 0 warnings potentially fixable with the `--fix` option.

Seems it doesn't auto-fix the quotes at the moment, the rest is fixed properly. Here is my configuration:

module.exports = {
    plugins: ['prettier'],
    rules: {
        'prettier/prettier': [
            'error',
            {
                printWidth: 120,
                tabWidth: 4,
                singleQuote: true,
                trailingComma: 'all',
                bracketSpacing: false,
            },
        ],
    },
};

CONTRIBUTING.md

It would be nice to link to a contributing guide to provide tips for debugging issues that come up

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.