Code Monkey home page Code Monkey logo

prettierx's Introduction

prettierX - a less opinionated fork of Prettier

License: MIT npm

An unofficial fork of the Prettier code formatter, intended to provide some additional options to help improve consistency with "Standard JS" (feross/standard) and Flet/semistandard. This fork is an attempt to pick up where arijs/prettier-miscellaneous left off.

Major THANKS

Major thanks is due to @adalinesimonian for contributions in PR #603 that enabled updates from Prettier 2.3.2.

prettierX as a Prettier plugin

prettier-plugin-x - provides the additional formatting options in a prettier plugin

CLI Usage

Quick CLI usage:

prettierx <options> <file(s)>

Additional prettierX options

  • --align-object-properties (alignObjectProperties: true): Align colons in multiline object literals (not applied with any of the JSON parsers).
  • --offset-ternary-expressions (offsetTernaryExpressions: true): Indent and align ternary expression branches more consistently with "Standard JS" (similar to the corresponding eslint option).
  • --space-before-function-paren (spaceBeforeFunctionParen: true): Put a space before function parenthesis in all declarations (similar to the corresponding eslint option). (Default is to put a space before function parenthesis for untyped anonymous functions only.)
  • --generator-star-spacing (generatorStarSpacing: true): Put spaces around the star (*) in generator functions (before and after - similar to the corresponding eslint option). (Default is after only.)
  • --yield-star-spacing (yieldStarSpacing: true): Put spaces around the star (*) in yield* expressions (before and after - similar to the corresponding eslint option). (Default is after only.)
  • --no-indent-chains (indentChains: false): Disable indents at the start of chained calls.
  • --break-before-else (breakBeforeElse: true): Always add a line break before else.
  • --import-formatting <auto|oneline> (importFormatting: "<auto|oneline>"): Formatting of import statements, may be oneline to avoid conflict with VSCode "Organize Imports" feature.
  • --html-void-tags (htmlVoidTags: true): Format void HTML elements as void tags.
  • --break-long-method-chains (breakLongMethodChains: true): Break method chains with more than 3 method calls, like Prettier 1.x.
  • --array-bracket-spacing (arrayBracketSpacing: true): Put spaces between array brackets (similar to the corresponding eslint option). Status: experimental, with limited testing.
  • --css-paren-spacing (cssParenSpacing: true): Put spaces between parens in CSS, WordPress style. Status: experimental, with limited testing.
  • --computed-property-spacing (computedPropertySpacing: true): Put spaces between computed property brackets (similar to the corresponding eslint option). Status: experimental, with limited testing.",
  • --space-in-parens (spaceInParens: true): Print spaces in between parens, WordPress style (similar to the corresponding eslint option). Not recommended in combination with the default arrowParens: "always" option. Status: experimental, with limited testing.
  • --space-unary-ops (spaceUnaryOps: true): Put spaces after unary operator symbols, except in the middle of !! (similar to the corresponding eslint option). Status: experimental, with limited testing.
  • --template-curly-spacing (templateCurlySpacing: true): Put spaces between template curly brackets (similar to the corresponding eslint option). Status: experimental, with limited testing.
  • --type-angle-bracket-spacing (typeAngleBracketSpacing: true): Put spaces between type angle brackets. Status: experimental, with limited testing.
  • --type-bracket-spacing (typeBracketSpacing: true): Put spaces between type brackets. Status: experimental, with limited testing.
  • --no-export-curly-spacing (exportCurlySpacing: false): Put or disable spaces between export curly braces.
  • --no-import-curly-spacing (importCurlySpacing: false): Put or disable spaces between import curly braces.
  • --no-object-curly-spacing (objectCurlySpacing: false): Disable spaces between object curly braces (similar to the corresponding eslint option).
  • --no-graphql-curly-spacing (graphqlCurlySpacing: false): Disable spaces between curly braces for GraphQL.
  • --no-yaml-bracket-spacing (yamlBracketSpacing: false): Disable spaces between brackets / curly braces for YAML.
  • --no-type-curly-spacing (typeCurlySpacing: false): Disable spaces between type curly braces.

(See docs/options.md for more information.)

"Standard JS" formatting options

The following options should be used to format the code as consistently as possible with "Standard JS":

  • --arrow-parens avoid (arrowParens: "avoid")
  • --generator-star-spacing (generatorStarSpacing: true)
  • --space-before-function-paren (spaceBeforeFunctionParen: true)
  • --single-quote (singleQuote: true)
  • --jsx-single-quote (jsxSingleQuote: true)
  • --no-semi (semi: false)
  • --offset-ternary-expressions (offsetTernaryExpressions: true)
  • --yield-star-spacing (yieldStarSpacing: true)
  • --trailing-comma none (trailingComma: "none")

Note that this tool does not follow any of the other "Standard JS" rules. It is recommended to use this tool together with eslint, in some form, to archive correct formatting according to "Standard JS".

Any known conflicts with "Standard JS" will be tracked in open issues with the conflict-with-standard tag.

some recommended options

  • --arrow-parens avoid (arrowParens: "avoid"), especially in combination with --space-in-parens (spaceInParens: true).
  • --break-long-method-chains (breakLongMethodChains: true)
  • --offset-ternary-expressions (offsetTernaryExpressions: true)

options removed

  • --no-align-ternary-lines - replaced with: --offset-ternary-expressions
  • --paren-spacing - replaced with finer-grained options:
    • --array-bracket-spacing
    • --css-paren-spacing
    • --computed-property-spacing
    • --space-in-parens
    • --space-unary-ops
    • --template-curly-spacing
    • --type-angle-bracket-spacing
    • --type-bracket-spacing
  • no-bracket-spacing - replaced with finer-grained options:
    • --no-export-curly-spacing
    • --no-import-curly-spacing
    • --no-object-curly-spacing
    • --no-graphql-curly-spacing
    • --no-yaml-bracket-spacing
    • --no-type-curly-spacing

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne()
);

Integration with eslint

A couple packages by @aMarCruz (Alberto Martínez):


Contributing

See CONTRIBUTING.md.

prettierx's People

Contributors

azz avatar bakkot avatar bnjmnt4n avatar brodybits avatar dcyriller avatar dependabot-preview[bot] avatar dependabot[bot] avatar despairblue avatar duailibe avatar evilebottnawi avatar existentialism avatar fisker avatar ikatyang avatar j-f1 avatar jameshenry avatar jlongster avatar josephfrazier avatar kachkaev avatar karl avatar lipis avatar lydell avatar mitermayer avatar rattrayalex avatar renovate[bot] avatar simenb avatar sosukesuzuki avatar suchipi avatar thorn0 avatar vjeux avatar yamafaktory 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

prettierx's Issues

unable to download parse-srcset from github

problem

i use a private npm registry, but parse-srcset is getting pulled from github, which is offlimits in my CI env 😭

"parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",

discussion

could we move this to an npm hosted version of srcset, or do we really need a particular sha? perhaps a npm publish could be acheived?

[prettierx] verbose ternary formatting

From issues such as issue #41 and prettier/prettier#5814, I am starting to wonder if we should consider a better way to format ternary expressions.

As described in prettier/prettier#5814 (comment) & prettier/prettier#5814 (comment), my idea would be to format JavaScript & TypeScript ternaries just like Prettier formats ternaries in JSX:

const result = type === 'first' ? (
  getFirstThing()
) : type === 'second' ? (
  getSecondThing()
) : (
  getOtherThing()
)

I tried the following update and it seems to do what we want here:

--- a/src/language-js/printer-estree.js
+++ b/src/language-js/printer-estree.js
@@ -370,6 +370,7 @@ function printTernaryOperator(path, options, print, operatorOptions) {
   const lastConditionalParent = previousParent;
 
   if (
+    true || // [prettierx option goes here instead of `true`]
     operatorOptions.shouldCheckJsx &&
     (isJSXNode(testNode) ||
       isJSXNode(consequentNode) ||

/cc @aMarCruz @sheerun

Conflict with standard in nested ternary expression

Prettier 1.16.4
Playground link

--parser babylon

Input:

export const foo = function (r, isSpace) {
  const type = /work|trabajo|empresa|negocio/i.test(r.Type)
    ? 't'
    : /home|hogar|Personal|Particular|casa/i.test(r.Type)
      ? ''
      : null

  return type
}

Output:

export const foo = function(r, isSpace) {
  const type = /work|trabajo|empresa|negocio/i.test(r.Type)
    ? "t"
    : /home|hogar|Personal|Particular|casa/i.test(r.Type)
    ? ""
    : null;

  return type;
};

Expected behavior:

The Input must be preserved.

The ESLint indent rule for StandardJS has flatTernaryExpressions: true, as seen in enforce consistent indentation (indent).

@brodybits , thanks for your awesome fork!

[prettierx] make the estree printer (more) pluggable

src/language-js/printer-estree.js seems to be a monolithic set of functions to format all possible elements of an estree that comes in some form from the parser

I wonder if there could be a way to make this functionality more pluggable somehow, in a similar fashion to the way Babel and ESLint can work with parsing, analysis, and formatting plugins.


related (2021):

  • prettier/prettier#4424 - support library-specific plugin
  • #418 - VS Code support
  • #8 - provide the additional formatting options in a Prettier plugin, which is now working in prettier-plugin-x

[prettierx] document --no-semi pitfall & recommended solution

See prettier/prettier#5903:

Input:

const str = 'abc'

[1, 2, 3].forEach(secondaryEffectFn)

It is using ASI, which is accepted by Prietter and generates this

Output:

const str = 'abc'[(1, 2, 3)].forEach(secondaryEffectFn)

This is valid and correct JavaScript but clearly not desired.

The recommended solution is to use ESLint to catch this kind of a pattern before using Prettier or prettierx.

This needs to be documented here and in Prettier itself.

quote-props: [“error”, “consistent-as-needed”]

I think this is the ideal way to format objects with properties.

I would love to do this kind of formatting for a project like Cordova.

I think this idea is inconsistent with “Standard JS” and Prettier, which both do quote-props: [“error”, “as-needed”] (if I am not mistaken).

switch-case indentation should be optional

Looking for an option to not indent cases:

switch(type) {
case "one":
  // ...
case "two": {
  let foo = "bar"
  // ...
  break
}
case "three": {
  let something = "here"
  // ...
  break
}}

Cannot get normal prettier to cooperate w/ our style guidelines here. The reason for this is we write Go and TypeScript code, and Go mandates case formatting be inline, so we have standardized on that. We try to keep our formatting standards as close as possible between languages.

So I'm looking for a fork to provide such an option. Unfortunately there isn't much out there besides prettier.

If I could have my way, I would like a tslint plugin that handled the line wrapping and use the other auto-fix rules for everything else. But nothing like that exists that I know of.

Mirror Version of Prettier

It would be cool if the version of this module would mirror the (minor) version of prettier it is forking, e.g. currently 1.16.X. The reason for this is that some tools (e.g. WebStorm) have dedicated functionality for prettier, that allows for pointing to a different binary, but they do a version check before. After editing the files' version from 0.6.X to 1.16.x in my case, prettierx works as a replacement without any issues.

I get that it's not SemVer, but maybe something to consider :)

Conflict with standard in ternary returning objects

Prettierx 0.3.0

--generator-star-spacing
--yield-star-spacing
--space-before-function-paren
--no-semi
--jsx-single-quote
--single-quote

Input:

let isSpace = false

const dress = isSpace ? {
      spaceSuit: 3,
      oxygenCylinders: 6
    } : {
      shirts: 3,
      paints: 3
    }

Output:

let isSpace = false

const dress = isSpace
  ? {
      spaceSuit: 3,
      oxygenCylinders: 6
    }
  : {
      shirts: 3,
      paints: 3
    }

Expected behavior:

The output should be compatible with standard. i.e. it should be something like

let isSpace = false

const dress = isSpace
  ? {
    spaceSuit: 3,
    oxygenCylinders: 6
  }
  : {
    shirts: 3,
    paints: 3
  }

Doesn't this mean prettierx can't achieve standard like formatting or am I missing something ?

Any options for multi-line destructuring?

I'm looking for a solution to prettier/prettier#2550 - Keep multi-line formatting for destructuring assignment.

It's really my only problem with prettier. Ideally, I'd like prettier to just not re-wrap my destructuring when I've chosen to put it on separate lines, similar to how it treats object literals.

Update some dependencies

From npm outdated some "dev", "beta", and "rc" dependency versions have been superseded by stable versions. Dependencies need to be updated. It would be ideal if the dependencies would be updated on the upstream prettier repository, as was already attempted in prettier#5562.

[prettierx] yarn audit issues

yarn audit currently shows 499 vulnerabilities.

While most of these vulnerabilities would lie in the devDependencies, and I would not expect any major security vulnerabilities in practice, I would like to get these resolved if possible.

Note that unlike prettier, there is no need to support Node.js 4 in prettierx, and I would like to drop Node.js versions 6 and 8 in the near future (see #6).

disabled space-before-function-paren adds a space between generic and function paren

Edited, initial version was not correct

I came across the weird and likely wrong behavior with formatting of the next lines of code

function foo<T>(x: T): T {
  return x
}

Even if I don't pass --space-before-function-paren flag (default value is false), space is added between foo<T extends number> and (x: T),

so the result is:

function foo<T> (x: T): T { // <-- space between <T> and (x: T)
  return T
}

Could you please confirm it's an issue?

Bug with selfclosing JSX and comments in TS ?

Hi @brodybits ,
I have an issue after upgrading my eslint-plugin-prettierx to prettierx 0.7 that cannot be reproduced in the Prettier playground.
In this fragment the JSDoc comment is marked for deletion:

image

Have you seen something like this before?

The error is present with ESLint 5.16 and 6.0, with @typescript-eslint/parser 1.9 and 1.11

This is the config of prettierx:

{
  "alignTernaryLines": false,
  "arrowParens": "avoid",
  "bracketSpacing": true,
  "endOfLine": "lf",
  "generatorStarSpacing": true,
  "indentChains": true,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": false,
  "printWidth": 92,
  "quoteProps": "consistent",
  "semi": false,
  "singleQuote": true,
  "spaceBeforeFunctionParen": true,
  "trailingComma": "es5",
  "yieldStarSpacing": true,
  "overrides": [
    {
      "files": "src/lib/toPlainLowerCase.ts",
      "options": {
        "printWidth": 320
      }
    }
  ]
}

It is not happening if <Card contact={contact} /> is closed: <Card contact={contact}></Card>, but prettierx removes </Card> forcing to selfclose.

Any help is appreciated. Thanks.

[prettierx] npm installation warning messages

I now get the following warning messages when installing prettierx, no different from installing from GitHub:

/Users/brodybits/dev/nvs/node/10.17.0/x64/lib/node_modules/prettierx/bin/prettierx.js
npm WARN [email protected] requires a peer of @angular/compiler@^6.0.0 || ^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.

I think this issue is caused by removing the special production build as discussed in #48.

Inconsistent formatting of nested ternary expressions

This relates to sheerun/prettier-standard#76

Here's example formatting of prettierx with indents on nested ternaries enabled:

search.premium
  ? commission => {
    return suggestions.hits.map(hit => something(hit))
  }
  : something
    ? commission => {
      return suggestions.hits.map(hit => something(hit))
    }
    : null

The core of this issue is that it's possible to configure prettierx to add extra indents to nested ternary expressions, but it also enables another extra formatting rule described below:

function is normally formatted with indentation:

commission => {
  return suggestions.hits.map(hit => something(hit))
}

but when ternary expression is used (with --align-ternary-lines=false option that enables indents on nested ternaries) it doesn't have it:

search.premium
  ? commission => {
    return suggestions.hits.map(hit => something(hit))
  }
  : () => onOpen()

Command used:

prettierx --generator-star-spacing --space-before-function-paren --single-quote --jsx-single-quote --no-semi --yield-star-spacing --align-ternary-lines=false

The real issue with this formatting is that's what standard --fix actually does! So technically is nothing wrong with prettierx, but for me it seems indeed this is wrong decision and the indentation should be at the level of expression after ?, not the ? itself (this doesn't prevent expressions being indented for each level of ?:):

search.premium
  ? commission => {
      return suggestions.hits.map(hit => something(hit))
    }
  : () => onOpen()

Unfortunately this also means formatting would be divergent from what standard.js does.

In the end the correct code, with just indents on nested ternaries enabled, is:

search.premium
  ? commission => {
      return suggestions.hits.map(hit => something(hit))
    }
  : something
    ? commission => {
        return suggestions.hits.map(hit => something(hit))
      }
    : null

NOTICE: no bundled TypeScript implementation, no special prod build

The TypeScript implementation from the typescript package is no longer bundled with prettierx, and prod build is no longer done as of prettierx 0.9.0.

It is desired to include and support use of TypeScript via babel-ts parser as proposed in prettier/prettier#6400, once it is ready for real-world usage.

Rationale:

  • I personally find the idea of automatically embedded implementation of TypeScript in the generated bundle, even with tree shaking, to be excessive in added complexity.
  • Since TypeScript is under the longer Apache 2.0 license statement, I think any package embedding TypeScript should technically fall under that license.

P.S. Here are some known side effects:

browser build no longer supported

A side effect of removing the prod build (#48) is that use in a browser build (https://prettier.io/docs/en/browser.html) is no longer expected to work.

I think it would be ideal if we could add a browser entry to package.json with a limited number of substitutions to make this package work in a browser ref:


Update June 2021: This means that the information in docs/browser.md does not apply for prettierX.

Some form of browser build support is under consideration for the future. And a switch to ES modules would likely increase the chances of working in more and more environments such as modern browsers and Deno out of the box.

The recommended solution for now is to use a bundler such as Rollup or Webpack.

Brackets same line Issue/template literals issue

Prettier 1.16.1
Playground link

# Options (if any):
# using prettier-standard package

Input:

docRef.update({[`schedule.${this.state.currDbLoc}.submission`]: selectedSubmission})

// -- or --

docRef.update({
  [`schedule.${this.state.currDbLoc}.submission`]: selectedSubmission
})

Output:

docRef
            .update({
              [`schedule.${
                this.state.currDbLoc
              }.submission`]: selectedSubmission
            })

Expected behavior:
Should produce (or stay as):

docRef.update({
  [`schedule.${this.state.currDbLoc}.submission`]: selectedSubmission
})

I'm using the prettier-standard package which uses this package to format and I'm getting this really weird formatting using a template literal inside an object key.

This seems partially like an issue with brackets on the same line rule of standard not being followed, and something else to do with the template literal.

Apart from this issue I do also have issues happening just with the brackets on same line rule not being followed, I just thought this one would showcase more.

Fix spacing for TS trick in TSX to define generics

There is a trick how to force parser to think it's a generic and not TSX code in .tsx file
typescript-eslint/typescript-eslint#1457

prettierx removes space after comma at <T,>: const MyComponent = <T, >({x, y, z}: Props<T>) => {…}, eslint standard config on the other hand expects this space.

Probably it can be an issue at prettier-standard instead, but I don't see an option to configure having this space only for generics

[prettierx] interesting links

@typescript-eslint/typescript-estree brings typescript as peer dependency

When someone installs prettier-standard (which depends on prettierx) without typescript as peer-dependency he/she gets following warning:

/usr/local/bin/prettier-standard -> /usr/local/lib/node_modules/prettier-standard/src/cli.js
npm WARN [email protected] requires a peer of @angular/compiler@^6.0.0 || ^7.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.

This is because prettierx depends on angular-estree-parser which requires @angular/compiler@^6.0.0 as peer dependency. Also @typescript-eslint/typescript-estree which indrectly requires tsutils which requires typescript as peer dependency.

I'm leaving this issue here without suggestion how to fix it because I don't know how.

Conflict with standard in computed function names

Prettier 1.16.4
Playground link

--parser babylon
--no-semi
--single-quote

Input:

export class Foo {
  static [Symbol.hasInstance] (obj) {
    return 'bar' in obj
  }
}

Output:

export class Foo {
  static [Symbol.hasInstance](obj) {
    return 'bar' in obj
  }
}

Expected behavior:
Should retain the space before the function parentheses.

[prettierx] known issue with --align-object-properties in standard test

Issue demonstrated in PR #17 where using --align-object-properties leads to the following exception:

    TypeError: Cannot read property 'raw' of undefined

      226 |       : n.raw
      227 |       ? n.raw.length
    > 228 |       : n.extra.raw
          |                 ^
      229 |       ? n.extra.raw.length
      230 |       : undefined;
      231 | 

      at getPropertyPadding (src/language-js/printer-estree.js:228:17)
      at FastPath.call (src/common/fast-path.js:69:18)
      at printPathNoParens (src/language-js/printer-estree.js:1507:38)
      at Object.genericPrint [as print] (src/language-js/printer-estree.js:96:30)
      at callPluginPrintFunction (src/main/ast-to-doc.js:126:18)
      at comments.printComments.p (src/main/ast-to-doc.js:63:14)
      at Object.printComments (src/main/comments.js:488:19)
      at printGenerically (src/main/ast-to-doc.js:61:22)
      at path.each.childPath (src/language-js/printer-estree.js:1403:22)
      at FastPath.each (src/common/fast-path.js:103:7)

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.