Giter Site home page Giter Site logo

prettier / prettier-vscode Goto Github PK

View Code? Open in Web Editor NEW
5.0K 46.0 446.0 103.1 MB

Visual Studio Code extension for Prettier

Home Page: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

License: MIT License

TypeScript 86.78% JavaScript 10.29% CSS 0.06% HTML 0.43% PHP 0.90% Vue 0.07% SCSS 0.24% Shell 0.06% Dockerfile 0.95% Handlebars 0.22%
formatter typescript visual-studio-code visual-studio-code-extension

prettier-vscode's Introduction

Prettier Formatter for Visual Studio Code

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular HANDLEBARS · Ember · Glimmer
GraphQL · Markdown · YAML
Your favorite language?

Build Status VS Code Marketplace Downloads VS Code Marketplace Installs code style: prettier Follow Prettier on Twitter

Installation

Install through VS Code extensions. Search for Prettier - Code formatter

Visual Studio Code Market Place: Prettier - Code formatter

Can also be installed in VS Code: Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.

ext install esbenp.prettier-vscode

Default Formatter

To ensure that this extension is used over other extensions you may have installed, be sure to set it as the default formatter in your VS Code settings. This setting can be set for all languages or by a specific language.

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

If you want to disable Prettier on a particular language you can either create a .prettierignore file or you can use VS Code's editor.defaultFormatter settings.

The following will use Prettier for all languages except Javascript.

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "<another formatter>"
  }
}

The following will use Prettier for only Javascript.

{
  "editor.defaultFormatter": "<another formatter>",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

Additionally, you can disable format on save for specific languages if you don't want them to be automatically formatted.

{
  "[javascript]": {
    "editor.formatOnSave": false
  }
}

Prettier Resolution

This extension will use prettier from your project's local dependencies (recommended). When the prettier.resolveGlobalModules is set to true the extension can also attempt to resolve global modules. Should prettier not be installed locally with your project's dependencies or globally on the machine, the version of prettier that is bundled with the extension will be used.

To install prettier in your project and pin its version as recommended, run:

npm install prettier -D --save-exact

NOTE: You will be prompted to confirm that you want the extension to load a Prettier module. This is done to ensure that you are not loading a module or script that is not trusted.

Prettier Version 3

Prettier's preview version 3 is supported as of version 9.12.0. It is not included in the extension by default, but can be used by installing locally in your project. Version 10.0.0 of this extension will include prettier 3.0.0 after it is out of preview. To try version 3 now run the following in your project:

Plugins

This extension supports Prettier plugins when you are using a locally or globally resolved version of prettier. If you have Prettier and a plugin registered in your package.json, this extension will attempt to register the language and provide automatic code formatting for the built-in and plugin languages.

Configuration

There are multiple options for configuring Prettier with this extension. You can use VS Code settings, prettier configuration files, or an .editorconfig file. The VS Code settings are meant to be used as a fallback and are generally intended only for use on non-project files. It is recommended that you always include a prettier configuration file in your project specifying all settings for your project. This will ensure that no matter how you run prettier - from this extension, from the CLI, or from another IDE with Prettier, the same settings will get applied.

Using Prettier Configuration files to set formatting options is the recommended approach. Options are searched recursively down from the file being formatted so if you want to apply prettier settings to your entire project simply set a configuration in the root. Settings can also be configured through VS Code - however, these settings will only apply while running the extension, not when running prettier through the command line.

Configuring Default Options

Some users may not wish to create a new Prettier config for every project or use the VS Code settings. In order to set a default configuration, set prettier.configPath. However, be careful, if this is set this value will always be used and local configuration files will be ignored.

Visual Studio Code Settings

You can use VS Code settings to configure prettier. Settings will be read from (listed by priority):

  1. Prettier configuration file
  2. .editorconfig
  3. Visual Studio Code Settings (Ignored if any other configuration is present)

NOTE: If any local configuration file is present (i.e. .prettierrc) the VS Code settings will NOT be used.

Usage

Using Command Palette (CMD/CTRL + Shift + P)

1. CMD + Shift + P -> Format Document
OR
1. Select the text you want to Prettify
2. CMD + Shift + P -> Format Selection

Keyboard Shortcuts

Visual Studio Code provides default keyboard shortcuts for code formatting. You can learn about these for each platform in the VS Code documentation.

If you don't like the defaults, you can rebind editor.action.formatDocument and editor.action.formatSelection in the keyboard shortcuts menu of vscode.

Format On Save

Respects editor.formatOnSave setting.

You can turn on format-on-save on a per-language basis by scoping the setting:

// Set the default
"editor.formatOnSave": false,
// Enable per-language
"[javascript]": {
    "editor.formatOnSave": true
}

Format Selection

Format selection works on several languages depending on what Prettier itself supports. The following languages currently are supported:

javascript
javascriptreact
typescript
typescriptreact
json
graphql
handlebars

Format Document (Forced)

If you would like to format a document that is configured to be ignored by Prettier either because it is in a .prettierignore file or part of a normally excluded location like node_modules, you can run the command Format Document (Forced) to force the document to be formatted. Forced mode will also ignore any config for requirePragma allowing you to format files without the pragma comment present.

Linter Integration

The recommended way of integrating with linters is to let Prettier do the formatting and configure the linter to not deal with formatting rules. You can find instructions on how to configure each linter on the Prettier docs site. You can then use each of the linting extensions as you normally would. For details refer to the Prettier documentation.

Workspace Trust

This extension utilizes VS Code Workspace Trust features. When this extension is run on an untrusted workspace, it will only use the built in version of prettier. No plugins, local, or global modules will be supported. Additionally, certain settings are also restricted - see each setting for details.

Settings

Prettier Settings

All prettier options can be configured directly in this extension. These settings are used as a fallback when no configuration file is present in your project, see the configuration section of this document for more details. For reference on the options see the prettier documentation.

The default values of these configurations are always to their Prettier 2.0 defaults. In order to use defaults from earlier versions of prettier you must set them manually using your VS Code settings or local project configurations.

prettier.arrowParens
prettier.bracketSpacing
prettier.endOfLine
prettier.htmlWhitespaceSensitivity
prettier.insertPragma
prettier.singleAttributePerLine
prettier.bracketSameLine
prettier.jsxBracketSameLine
prettier.jsxSingleQuote
prettier.printWidth
prettier.proseWrap
prettier.quoteProps
prettier.requirePragma
prettier.semi
prettier.singleQuote
prettier.tabWidth
prettier.trailingComma
prettier.useTabs
prettier.vueIndentScriptAndStyle
prettier.embeddedLanguageFormatting

Extension Settings

These settings are specific to VS Code and need to be set in the VS Code settings file. See the documentation for how to do that.

prettier.enable (default: true)

Controls whether prettier is enabled or not. You must restart VS Code when you change this setting.

prettier.requireConfig (default: false)

Require a prettier configuration file to format files. Untitled files will still be formatted using the VS Code Prettier configuration even with this option set to true.

prettier.ignorePath (default: .prettierignore)

Supply the path to an ignore file such as .gitignore or .prettierignore. Files which match will not be formatted. Set to null to not read ignore files.

Note, if this is set, this value will always be used and local ignore files will be ignored.

Disabled on untrusted workspaces

prettier.configPath

Supply a custom path to the prettier configuration file.

Note, if this is set, this value will always be used and local configuration files will be ignored. A better option for global defaults is to put a ~/.prettierrc file in your home directory.

Disabled on untrusted workspaces

prettier.prettierPath

Supply a custom path to the prettier module. This path should be to the module folder, not the bin/script path. i.e. ./node_modules/prettier, not ./bin/prettier.

Disabled on untrusted workspaces

prettier.resolveGlobalModules (default: false)

When enabled, this extension will attempt to use global npm or yarn modules if local modules cannot be resolved.

NOTE: This setting can have a negative performance impact, particularly on Windows when you have attached network drives. Only enable this if you must use global modules. It is recommended that you always use local modules when possible.

Note: Disabling a language enabled in a parent folder will prevent formatting instead of letting any other formatter to run

Disabled on untrusted workspaces

prettier.documentSelectors

A list of glob patterns to register Prettier formatter. Typically these will be in the format of **/*.abc to tell this extension to register itself as the formatter for all files with the abc extension. This feature can be useful when you have overrides set in your config file to map custom extensions to a parser.

It is likely you will need to also update your prettier config. For example, if I register the following document selector by itself, Prettier still won't know what to do with that file. I either need a Prettier extension that formats .abc file format or I need to configure Prettier.

{
  "prettier.documentSelectors": ["**/*.abc"]
}

To tell Prettier how to format a file of type .abc I can set an override in the prettier config that makes this file type use the babel parser.

{
  "overrides": [
    {
      "files": "*.abc",
      "options": {
        "parser": "babel"
      }
    }
  ]
}

Disabled on untrusted workspaces

prettier.useEditorConfig (default: true)

Whether or not to take .editorconfig into account when parsing configuration. See the prettier.resolveConfig docs for details.

Disabled on untrusted workspaces (always false)

prettier.withNodeModules (default: false)

Whether or not to process files in the node_modules folder.

Disabled on untrusted workspaces

Error Messages

Failed to load module. If you have prettier or plugins referenced in package.json, ensure you have run npm install

When a package.json is present in your project and it contains prettier, plugins, or linter libraries this extension will attempt to load these modules from your node_module folder. If you see this error, it most likely means you need to run npm install or yarn install to install the packages in your package.json.

Your project is configured to use an outdated version of prettier that cannot be used by this extension. Upgrade to the latest version of prettier.

You must upgrade to a newer version of prettier.

This workspace is not trusted. Using the bundled version of prettier.

You must trust this workspace to use plugins and local/global modules. See: Workspace Trust

prettier-vscode's People

Contributors

axetroy avatar azz avatar b3njamin avatar bpscott avatar cigit avatar coliff avatar dependabot-preview[bot] avatar dependabot[bot] avatar esbenp avatar fisker avatar garyking avatar gluxon avatar jarrodldavis avatar jhilker avatar josephfrazier avatar kostasmanionis avatar lostintangent avatar lrowe avatar mrbunker avatar nickmccurdy avatar ntotten avatar oliverjash avatar raineorshine avatar robinmalfait avatar rotu avatar samestep avatar sibiraj-s avatar sosukesuzuki avatar thorn0 avatar ulricgan 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prettier-vscode's Issues

Getting `Cannot read property 'prettier' of undefined` message

Hi,
Everything was working fine but then suddenly I began to receive the error message Cannot read property 'prettier' of undefined when trying to format the code. The only difference I remember is that I updated my VSCode extensions.
I uninstalled the extension, reload and the reinstalled again the extension but he problem remains.

I have VSCode 1.11.1 installed on Mac OSX 10.11.6 (El Capitan).

Results are different for prettier-vscode and prettier CLI

I have prettier v0.22.0 installed locally in my project. When I use it from command line output differs from what I get when I do Format Document from command palette.
I do not have any other formatting extensions installed and I use default options for prettier.

image

Peer dependency or similar behaviour

Is there any way that we dont need to wait this package updated to have a new version of prettier?

Maybe the extension can check if prettier is installed in the user node_modules?

The differencies between plugin and command prettier result

The source code resulted from Prettier VS Code plugin is different from results of command prettier --write /somefile/*.js . The difference is occured in keys inserted to React Component. This keys are not on newlines in results from plugin. See file with example testing_prettier.zip .

Input file:
testing_prettier.js

Output from plugin:
testing_prettier_afterplugin.js

Output from command:
testing_prettier_aftercommand.js

The keys named key, className and onClick are delimited with new line in result from command, I think that is right.

cannot provide options

there is no way to provide options in config and seems it doesn't do anything to my js code

Flow parser removes line breaks

Hello,

I would like to know if it's actually possible to disable this extensions for certains files? Like the JSON ones. Maybe by using a glob in settings.

Nothing happens

When I select prettier from the command menu absolutely nothing happens. Thoughts?

Formatting is worse than using the CLI Tool

Description

I have a JSX File that I want to be prettier. I compare prettier CLI and your vscode plugin.

Expected

It looks the same in CLI and vscode plugin

Actual

It looks different

Configuration:

  "editor.formatOnSave": true,
  "prettier.singleQuote": true,
  "prettier.parser": "flow",
  "prettier.printWidth": 120,

Versions

prettier: 0.22.0
vscode: 1.11.1
plugin: 0.12.0

other plugins:

  • eslint 1.2.8
  • flow 0.5.0
  • some themes

CLI command

prettier --write --print-width 120 --single-quote --trailing-comma all --parser flow MinimalExample.jsx

Input and CLI output

import React, { Component } from 'react';
import { func1, arr1 } from 'somewhere';

// elements
export default class Example extends Component {
  render() {
    describe('', () => {
      describe('', () => {
        describe('', () => {
          func1(arr1[0]).toEqual({
            first_name: 'Garfield',
            last_name: 'the Cat',
            profession: 'The cat food tester',
            employer_name: 'CK',
            zip_code: '5000',
            city: 'Aarau',
            phone: '+41 79 230 98 76'
          });
        });
      });
    });

    return <h1 className="demo">hi</h1>;
  }
}

vscode output

import React, { Component } from 'react';
import { func1, arr1 } from 'somewhere';

// elements
export default class Example extends Component {
  render() {
    describe('', () => {
      describe('', () => {
        describe('', () => {
          func1(
            arr1[0],
          ).toEqual({ first_name: 'Garfield', last_name: 'the Cat', profession: 'The cat food tester', employer_name: 'CK', zip_code: '5000', city: 'Aarau', phone: '+41 79 230 98 76' });
        });
      });
    });

    return <h1 className='demo'>hi</h1>;
  }
}

The annoyances

  • it puts single quotes into the markup
  • it puts the object into one line

TSX falls back to JS

TypeScript React falls back to JavaScript. It would be better to fall back to JSX (JavaScript React).

[Fixed in Prettier@next] Unexpected whitespace added in JSX

I just noticed unexpected formatting inside a simple block of JSX using version 0.12.0 in VS Code 1.10.2. As you'll see below, whitespace is being added before and after the content of the Button component. The prettier-vscode output is inconsistent with the online Prettier tool output. I also confirmed the output using the prettier-atom package (0.26.0) in Atom matches the online tool.

{/* Before prettier-vscode */}
<Button type="submit" color="primary">
  Save
</Button>

{/* After prettier-vscode */}
<Button type="submit" color="primary">
  {' '}
  Save{' '}
</Button>

Blank validation error when using "editor.formatonsave": true

Hi I get the following blank error when I save file with "editor.formatonsave": true

screen shot 2017-04-03 at 1 06 06 pm

These are the settings I am currently using:
{ "editor.cursorStyle": "line-thin", "editor.cursorBlinking": "phase", "editor.minimap.enabled": true, "editor.formatOnSave": true, "flow.useNPMPackagedFlow": true, "javascript.validate.enable": true, "prettier.parser": "flow", "prettier.singleQuote": true, "terminal.external.osxExec": "iTerm.app", "workbench.colorTheme": "Material Theme", "workbench.iconTheme": "vscode-icons" }

When I disable edit.formatonsave I do not get the error drop down in my screenshot, but of course it does not format the code, either.

Can anyone provide insight into what I might be doing wrong?

Error : Cannot find module 'jest-validate'

Hi everyone!

I'm using the latest version of Prettier - JavaScript formatter on macOS and running VsCode version 1.11.0 (Insider). I really like this plugin a lot and depend pretty heavy on it but it just stopped working a few days ago. Every time I wanna make use of this plugin I get the following error :

screen shot 2017-04-04 at 09 31 09

Here is the complete error message shown in the console:

screen shot 2017-04-04 at 09 34 14

I haven't installed any new extensions recently nor have I made changes to my settings.jsonfile.

Here are the settings I use for prettier :
"prettier.printWidth": 100, "prettier.singleQuote": true,

If I disable Prettier - JavaScript formatter the editor doesn't show the error message Cannot find module 'jest-validate' and it does format the code with the build-in options of VsCode.

I hope this issue gets resolved soon.
If any other information is needed please do ask. Anyways thank you for your work.

Use prettier from current workspace

Currently plugin uses internal dependency on prettier. I think it would be better to use prettier from current projects node_modules, if it exists.

What are the rules around what prettier version is used?

If I run prettier from the version installed in my project (from npm install --save-dev prettier), the output is different to that of the VS Code extension. I can see that the prettier version in the extension is fixed.

  1. Is it possible for the extension to use the local prettier if it exists instead of the one it provides?
  2. If not, is it possible to update the prettier version in this extension and if so, are you just going to have to manually update it all the time when a new prettier comes out?

Thanks for the great extension.

Prettify as you type

In the blog entry, it shows how live code reformating could happen. I don't know if I would like this option, it might be distracting or counter-productive. OTOH it could be awesome. Thoughts?

Some error messages should be complete

In some case, prettier throws error messages which are not ParseError.
Currently all error message are truncated and only the first line is shown which may not be enough to really understand what's going wrong.

  • ParseError is currently handled with an error message and "Show" action. This action will scroll to the error location.
  • OtherError show only the first line in an errorMessage. An example is in #54 (comment)

I think we should handle errors which have no .loc differently. It is not possible to print more than one line with window.showErrorMessage. An alternative for those may be to open an outputChanel.

Indentation on JSX part

Work fine, except on indentation on jsx file :(


    return (
      <ul
        className={messageListClassName}
        ref={el => {
            this.list = el; /* here */
          }} /* here */
      >
        {messageIds.map(id => <Message key={id} id={id} />)}
      </ul>
    );

Then correctly formatted, in command line

$ prettier --write src/**/*.js --single-quote --trailing-comma --bracket-spacing

Edit: prettier (v0.0.10)

Bracket Spacing not respecting []

Before upgrade to 0.7.0, brackets would be spaced: [ 'value' ] now they do not allow spacing: ['value'].

It still respects {}, but not square brackets :(

Prettier adds ';' and line-break when pasting

Hi guys,

can't figure out why but this extension keeps adding ';' and line-break when pasting small pieces of text.

So if i would copy: 'foo' and paste it where 'bar' is it would return the second part:

// when copying the first foo and pasting it over bar..
foo('something');
bar('something');
// this is the result..
foo('something');
foo;
('something');

My settings:

{
    "editor.fontFamily": "'Operator Mono', Menlo, Monaco, 'Courier New', monospace",
    "editor.tabSize": 2,
    "editor.fontSize": 16,
    "workbench.editor.showTabs": true,
    "editor.snippetSuggestions": "top",
    "window.zoomLevel": -2,
    "files.autoSave": "onWindowChange",
    "editor.wordWrap": "on",
    "terminal.integrated.fontSize": 16,
    "javascript.validate.enable": false,
    "emmet.syntaxProfiles": {
        "javascript": "html"
    },
    "files.associations": {
        "*.jsx": "javascriptreact"
    },
    "stylelint.enable": true,
    "css.validate": false,
    "vsicons.dontShowNewVersionMessage": true,
    "vsicons.projectDetection.disableDetect": true,
    "search.exclude": {
        "**/.git": true,
        "**/node_modules": true,
        "**/bower_components": true,
        "**/build": true,
        "**/dist": true,
        "**/stage": true,
        "**/typings": true,
        "**/.vscode": true,
        "**/.nyc-output": true
    },
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "Ember Frost",
    "typescript.check.tscVersion": false,
    "material-icon-theme.showUpdateMessage": false,
    "editor.formatOnSave": true,
    "prettier.printWidth": 80,
    "prettier.singleQuote": true,
    "editor.cursorStyle": "line",
    "window.reopenFolders": "none",
    "explorer.openEditors.visible": 0,
    "explorer.autoReveal": false,
    "editor.formatOnPaste": false,
    "workbench.editor.enablePreview": false,
    "files.hotExit": "off"
}

Endless loop in package.json

I enabled editor.formatOnSave and every time I open my package.json it tries to format it (prettier does not support formatting JSON files), then it saves, reformat, save, reformat... automatically. I don't get out of this loop.

feb-23-2017 08-32-06

can't get this to work

Installed with VSCode 1.9.1 on Ubuntu, reloaded, CTRL-SHIFT-P brings up VSCode's command palette, it doesn't format the code. Typing "prettier" in the command palette doesn't bring up anything. VSCode's Problems and Output panes don't show anything about Prettier, either.

Exact same problem with VSCode 1.10.2 on Mac OS. I've been using other VSCode plugins like Standard without problem. What's the trick to get prettier-vscode working?

Also, CMD-SHIFT-P is by default mapped to the command palette. Why use this for formatting?

Option to indent with tabs

Thanks for a superb plugin!
What our team is looking for is an option to select either to indent with spaces or tabs.
I am fully aware of the Spaces vs Tabs war, but the option to select one of them would be awesomeness!

Thanks!

Shebangs get removed

Adding a shebang line:
#!/usr/bin/env node
gets converted to a comment:
///usr/bin/env node
preventing the script from running as a standalone command.

I am using MacOS Sierra with VS Code and the prettier extension.

command 'prettier.format' not found

Hey, I just tried your plugin but unfortunately I cannot get it to work, I keep getting

command 'prettier.format' not found

Any idea why ?

Currently on osx, with vscode 1.8.1

In vscode console I can see this:

[Extension Host] Activating extension esbenp.prettier-vscode failed: {1}. extensionHost.ts:293
[Extension Host] Activating extension esbenp.prettier-vscode failed:  undefined extensionHost.ts:293

I tried with prettier installed globally and locally
Thanks :)

Please explain the options a little better.

editor.formatOnSave is an option I can find

I'm less certain of where to put printWidth, trailingComma, etc...

Do those have any kind of prefix? Seems like they should to keep them separate from other plugins, but I don't know what that prefix should be.

Could we get an example of the some of them in the format they should be in for settings.json?

Nested ternary operations

My VSCode User preferences:

{
    "prettier.printWidth": 120,
    "prettier.singleQuote": true
}

Original code:

const retVal = diff < -365 ? 'sameElse' :
  diff < -6 ? 'lastYear' :
  diff < -1 ? 'lastWeek' :
  diff < 0 ? 'lastDay' :
  diff < 1 ? 'sameDay' :
  diff < 2 ? 'nextDay' :
  diff < 7 ? 'nextWeek' :
  diff < 365 ? 'nextYear' : 'sameElse';

Expected:

const retVal = diff < -365 ?
      'sameElse' :
      diff < -6 ?
        'lastYear' :
        diff < -1 ?
          'lastWeek' :
          diff < 0 ?
            'lastDay' :
            diff < 1 ?
              'sameDay' :
              diff < 2 ?
                'nextDay' :
                diff < 7 ?
                'nextWeek' :
                  diff < 365 ?
                  'nextYear' :
                    'sameElse';

Result:

const retVal = diff < -365
      ? 'sameElse'
      : diff < -6
          ? 'lastYear'
          : diff < -1
              ? 'lastWeek'
              : diff < 0
                  ? 'lastDay'
                  : diff < 1
                      ? 'sameDay'
                      : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : diff < 365 ? 'nextYear' : 'sameElse';

2 issues here:

  1. The indents are set to 4 even though my user preferences specify a tab size of 2.
  2. The formatting sort of gives up breaking lines for ternary (see last line). I am guessing this is because it decides that the rest of the operation can fit in one line knowing that the ruler is set to 120. I would still like to give the annotation consistency. Keeping this "ladder" all the way to the end would make it more readable.

I am pretty sure my second point should be more of an issue for the prettier project itself but I thought there was some conversations I can get from here first.

Necessity of various configuration options?

This is not a bug nor aims at criticizing.
I'd like to open a discussion on the configuration bag. More precisely on tabWidth

Currently, the extension's option bag is passed nearly directly to prettier. Therefor we have the same configuration as prettier's, which is not a bad thing as it is easier to remember.

But we are duplicating some options between this extension and vscode's. Ignoring vscode's settings.

Options

prettier-vscode vscode
tabWidth editor.tabSize, editor.insertSpace, editor.detectIndentation
formatOnSave editor.formatOnSave

tab Width

It would be difficult to respect those settings entirely, because prettier doesn't indent with hard tabs yet and maybe won't. discussion But at least, tabSize and detectIndentation could be used.

format On Save

That is a one to one replacement and is (currently) the only option not passed to prettier.
Note: PR #18 removes formatOnSave in favor of editor.formatOnSave

My point

The trouble I see is having conflicting options. This goes even worse when you have multiple extension also duplicating options.

{ ext1.formatOnSave: true,
  ext2.formatOnSave: true,
  ext3.formatSave: true, // this one names it differently
  editor.formatOnSave: false
  ...
}

It is still possible to have settings per workspace and as of vscode 1.9: per language
I see no improvement in having an extension option, but I may miss something (I'm not a formatOnSave user)

Questions

  1. What do you think about removing options?
  2. Is it correct to respect tabSize but not insertSpace?
  3. Is there any option I've not seen which could be replaced/inferred?

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.