prettier/website/blog/2018-05-27-1.13.0.md

34 KiB

author authorURL title
Lucas Duailibe (@duailibe) https://twitter.com/duailibe Prettier 1.13: Conquering the web!

This releases adds support for several new syntax features, formatting fixes and first-class support for working in the browser.

Highlights

API/CLI

Prettier works in the browser!

This has been long wanted by the team and our users and we're finally announcing Prettier 1.13 has first-class support for running in the browser. In the past it required several hacks, but as of today you can just load the core bundle and the parsers you want to use.

<script src="https://unpkg.com/prettier@1.13.0/standalone.js"></script>
<script src="https://unpkg.com/prettier@1.13.0/parser-babylon.js"></script>
<script src="https://unpkg.com/prettier@1.13.0/parser-graphql.js"></script>
<script type="text/javascript">
var formatButton = document.querySelector("#format");
var textInput = document.querySelector("#input");
formatButton.addEventListener("click", function() {
  var value = textInput.value;
  textInput.value = prettier.format(value, {
    parser: "babylon",
    plugins: prettierPlugins
  });
});</script>

Read more about it in the docs or try it on this JS Bin.

Don't default to the JavaScript parser (#4528 by @duailibe)

In Prettier 1.12 and earlier, when running Prettier on a file without a file extension, Prettier would assume the file contained JavaScript. This lead to a couple of confusing bugs, namely:

  • If you ran prettier on your .git directory, it would reformat files and break your git repo.
  • If you tried to run prettier on html files, it would sometimes throw an error, but other times parse the HTML as JSX, and format it as if it was JSX (which was often unsafe).

In Prettier 1.13, we are changing this behavior. If Prettier cannot determine what language a file is from its extension, and the user has not manually specified a parser to use, Prettier will skip the file.

If you need to format files with unsupported or nonstandard extensions, you can use the --parser option to specify which parser to use. If you are piping file contents into stdin, make sure to include --stdin-filepath so that prettier can use the file extension to detect what language to parse the input as.

When using the JavaScript API, prettier.format and prettier.formatWithCursor will now throw an error if you do not include either parser or filepath in the options you pass in. It will also throw an error if you include filepath but not parser and the correct parser cannot be inferred from the file path.

prettier.getFileInfo() method and --file-info CLI option (#4341 by @kachkaev)

When invoking Prettier from the API, there was no way to find out if a file should be ignored or not (for .prettierignore) so editor integration plugins would have to implement this logic. Also, there was no way to find out if a file was supported by Prettier, so users would need to call Prettier anyway. In 1.13 there's a way to check if a parser will be inferred (and which one) and if the file is ignored or not before actually calling format.

You can read more about this in the docs.

Support for global Prettier and plugins (#4192 by @kachkaev)

When installing Prettier and plugins globally, Prettier was not able to automatically load plugins because it searched for them in the nearest package.json. Now Prettier will look for plugins in the node_modules directory it's installed in. Additionally, for cases where Prettier can't find the plugins automatically (because of other setups we haven't added support for), a new --plugin-search-dir option was added so you can specify where Prettier should search for plugins.

You can read more about this in the Plugin docs.

Improve cursor offset tracking (#4397 by @ds300)

Prettier 1.13 vastly improves the cursor offset tracking for several cases where Prettier was outputting the wrong location, making editor integrations move the cursor to an incorrect location.

JavaScript

Insert more parentheses in math expressions (#4413 and #4407 by @duailibe)

Prettier will now add parens around module operations when they're inside an additive operation or when mixing two different multiplicative operations, even though they're not necessary. This is to help more quickly understand a code snippet.

// Input
a % 10 - 5;
2 / 3 * 10 / 2 + 2;

// Output with Prettier 1.13
(a % 10) - 5;
((2 / 3) * 10) / 2 + 2;

Inline AngularJS tests that use inject (#4495 by @thorn0)

Prettier will now keep AngularJS tests with dependency injection in a single line, like it does for our other tests.

// Input:
it("has calculated the answer correctly", inject(function(DeepThought) {
  expect(DeepThought.answer).toBe(42);
}));

// Output with Prettier 1.12.1:
it(
  "has calculated the answer correctly",
  inject(function(DeepThought) {
    expect(DeepThought.answer).toBe(42);
  })
);

// Output with Prettier 1.13:
it("has calculated the answer correctly", inject(function(DeepThought) {
  expect(DeepThought.answer).toBe(42);
}));

Nicer line wrapping for D3 (#4285 by @1wheel, #4505 by @duailibe)

In Prettier 1.12 and earlier, chains that started with d3 and other short names were broken before the first .. In Prettier 1.13, we will not add a newline after the name if it is shorter than the indentation width.

// Input
d3.select('body')
  .append('circle')
  .at({ width: 30, fill: '#f0f' })
  .st({ fontWeight: 600 })

// Output with Prettier 1.12.1:
d3
  .select("body")
  .append("circle")
  .at({ width: 30, fill: "#f0f" })
  .st({ fontWeight: 600 });

// Output with Prettier 1.13:
d3.select("body")
  .append("circle")
  .at({ width: 30, fill: "#f0f" })
  .st({ fontWeight: 600 });

Format new describe.each table in Jest 23 (#4423 by @ikatyang)

Jest 23 introduced a new feature called data driven tests where you can describe examples to test in a table. Prettier 1.13 includes support for this feature, and will automatically indent the table when using data driven tests.

// Input
describe.each`
a|b|expected
${11   } | ${  1  }|${222}
${1-1}|${2+2}|${ 3333}
${2+1+2}|${1111}|${3}
`('$a + $b', ({a, b, expected}) => {
  test(`returns ${expected}`, () => {
    expect(a + b).toBe(expected);
  });

  test(`returned value not be greater than ${expected}`, () => {
    expect(a + b).not.toBeGreaterThan(expected);
  });

  test(`returned value not be less than ${expected}`, () => {
    expect(a + b).not.toBeLessThan(expected);
  });
});

// Output with Prettier 1.13
describe.each`
  a            | b        | expected
  ${11}        | ${1}     | ${222}
  ${1 - 1}     | ${2 + 2} | ${3333}
  ${2 + 1 + 2} | ${1111}  | ${3}
`("$a + $b", ({ a, b, expected }) => {
  test(`returns ${expected}`, () => {
    expect(a + b).toBe(expected);
  });

  test(`returned value not be greater than ${expected}`, () => {
    expect(a + b).not.toBeGreaterThan(expected);
  });

  test(`returned value not be less than ${expected}`, () => {
    expect(a + b).not.toBeLessThan(expected);
  });
});

Format functional composition more nicely (#4431 by@suchipi)

One of the most requested changes in Prettier was to format function composition better. This pattern is pretty common in functional programming libraries like RxJS, Redux, Lodash, and Ramda. In 1.13, Prettier now has an heuristic to detect this type of function composition and format it such that the composed functions are each on their own line. This improves readability when using functions like pipe, compose, flowRight, etc.

// Input
compose(
  sortBy(x => x),
  flatten,
  map(x => [x, x * 2])
);

pipe(
  filter(x => x % 2 === 0),
  map(x => x + x),
  scan((acc, x) => acc + x, 0)
);

// Output with Prettier 1.12.1
compose(sortBy(x => x), flatten, map(x => [x, x * 2]));

pipe(filter(x => x % 2 === 0), map(x => x + x), scan((acc, x) => acc + x, 0));

// Output with Prettier 1.13
compose(
  sortBy(x => x),
  flatten,
  map(x => [x, x * 2])
);

pipe(
  filter(x => x % 2 === 0),
  map(x => x + x),
  scan((acc, x) => acc + x, 0)
);

Keep parens around do expressions when needed and improve their formatting (#4479 by @existentialism)

In Prettier 1.12 and earlier, there were some cases where Prettier would remove parens around do expressions where it was not safe to do so, which would cause the code to become invalid. Those cases are now fixed in 1.13. Also, formatting of do expressions has been improved in general with this release.

// Input
(do {});
(do {} + 1);
(1 + do {});

() => do {
  var obj = { foo: "bar", bar: "foo" };
  for (var key in obj) {
    obj[key];
  }
};

// Output with Prettier 1.12
do {
};
do {
} + 1;
1 +
  do {
  };

() =>
  do {
    var obj = { foo: "bar", bar: "foo" };
    for (var key in obj) {
      obj[key];
    }
  };

// Output with Prettier 1.13
(do {});
(do {} + 1);
1 + do {};

() => do {
  var obj = { foo: "bar", bar: "foo" };
  for (var key in obj) {
    obj[key];
  }
};

Flow

Print classes mixins and implements correctly (#4326 by @existentialism)

In versions 1.12 and earlier, Prettier would incorrectly remove mixins and implements from flow libdef classes, which would change the meaning of the code. This has been fixed in 1.13.

// Input
declare class A implements B {}
declare class C mixins D {}

// Output with Prettier 1.12
declare class A {}
declare class C {}

// Output with Prettier 1.13
declare class A implements B {}
declare class C mixins D {}

Added support for the nullish coalescing operator and literal numeric separators (#4536 by @vjeux)

These JS features were already supported when using the default Babylon parser, but Prettier 1.13 adds support for them when using the Flow parser.

Added support for Flow new syntax features (#4543, #4540 and #4551 by @existentialism)

New features added to Flow are now supported by Prettier:

  • inline interfaces

    type A = interface { p: string};
    
  • explicit type arguments

    fnCall<string>("name");
    
  • proto modifier syntax

    declare class A { proto: T }
    

TypeScript

Added support for TypeScript import types (#4429 and #4438 by @ikatyang)

A new feature added in TypeScript 2.9 for describing the shapes of a module imported dynamically.

// Input
export const x: import("./foo") = { x: 0, y: 0 };

export let y: import("./foo2").Bar.I = { a: "", b: 0 };

export let shim: typeof import("./foo2") = { Bar: Bar2 };

// Output with Prettier 1.13
export const x: import("./foo") = { x: 0, y: 0 };

export let y: import("./foo2").Bar.I = { a: "", b: 0 };

export let shim: import("./foo2") = { Bar: Bar2 };

Added support for generic JSX elements in TypeScripts (#4268 by @ikatyang)

Another feature added in TypeScript 2.9 is the support for generics in JSX elements and Prettier 1.13 can now format them.

// Example:
<MyComponent<number> data={12} />

Added support for TaggedTemplateExpression typeParameters (#4353 by @ikatyang)

Also added in TypeScript 2.9, it's now possible to pass type parameters to template expression tags.

// Example:
export const RedBox = styled.div<{ foo: string }>`
  background: red;
  ${props => props.foo};
`;

Improve format of type casts with generics and unions (#4219 by @kpdonn)

// Input
const finalConfiguration =
  <Immutable.Map<string, any>>someExistingConfigMap.mergeDeep(fallbackOpts);

// Output with Prettier 1.12
const finalConfiguration = <Immutable.Map<
  string,
  any
>>someExistingConfigMap.mergeDeep(fallbackOpts);

// Output with Prettier 1.13
const finalConfiguration = <Immutable.Map<string, any>>(
  someExistingConfigMap.mergeDeep(fallbackOpts)
);

JSON

Split JSON and JSON5 parsers (#4367 and #4371 by @ikatyang, #4333 by @duailibe)

JSON5 is a superset of JSON that supports comments, trailing commas and unquoted property keys. Some files (like .babelrc) use JSON5, so comments, trailing commas, and unquoted property keys are allowed in those files. Other files (like package.json) do not use JSON5, so comments, trailing commas, and unquoted property keys are not allowed. Prettier previously had one parser and printer called JSON which was used for both, but maintaining both together led to some subtle bugs being introduced, notably around the /* @prettier */ pragma comment detection and insertion. With the two split apart, these bugs are fixed and Prettier is more robust.

Added json-stringify parser for JSON.stringify-style formatting (#4450 by @ikatyang)

One common complain with prettier was that it would format package.json and package-lock.json differently from how npm and yarn would, so if you ran an npm or yarn command, it could introduce prettier violations, and editing package.json could add line breaks that would later be removed when you next ran an npm or yarn command. This led to a lot of unnecessary diff noise and a bad user experience. In Prettier 1.13, a new parser/printer called json-stringify has been added that behaves the same as JSON.stringify, so that changes will not flip-flop back and forth when using prettier and npm/yarn. Also, this is now the default parser/printer for package.json and package-lock.json, so if you upgrade to the latest version of prettier, these noisy diffs will stop appearing without any configuration change on your part.

CSS/Less/SCSS

Improve format for SCSS maps (#4487 by @evilebottnawi)

/* Output with Prettier 1.12 */
a {
  @include section-type-1(
    $header: (margin: 0 0 $margin-base, text-align: left),
    $decoration:
      (
        type: base,
        margin: 0 auto -1px 0,
        primary-color: $brand-primary,
        secondary-color: $gray-light
      ),
    $title:
      (
        margin: 0 0 $margin-small,
        color: false,
        font-size: $font-size-h3,
        font-weight: false,
        line-height: $line-height-h3
      )
  );
}

/* Output with Prettier 1.13 */
a {
  @include section-type-1(
    $header: (
      margin: 0 0 $margin-base,
      text-align: left
    ),
    $decoration: (
      type: base,
      margin: 0 auto -1px 0,
      primary-color: $brand-primary,
      secondary-color: $gray-light
    ),
    $title: (
      margin: 0 0 $margin-small,
      color: false,
      font-size: $font-size-h3,
      font-weight: false,
      line-height: $line-height-h3
    )
  );
}

Improve format for @support at-rule (#4372 by @evilebottnawi)

/* Input */
@supports (transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {}

/* Output with Prettier 1.12 */
@supports (transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {
}

/* Output with Prettier 1.13 */
@supports (transform-style: preserve) or (-moz-transform-style: preserve) or
  (-o-transform-style: preserve) or (-webkit-transform-style: preserve) {
}

Markdown

Change unordered list symbol to a hyphen (#4440 by @ikatyang)

With the release of Markdown support in Prettier, we used GitHub BigQuery data and discovered that the * symbol was marginally more used than - for unordered lists. Since then, we have received massive feedback from the community that the - is actually preferred. Prettier 1.13 will now format unordered lists using the - symbol.

<!-- Input -->
* Top level list item 1
* Top level list item 2
  * Nested List item 1
  * Nested List item 2
    * Sub-Nested List item 1
    * Sub-Nested List item 2

<!-- Output with Prettier 1.12.1 -->
* Top level list item 1
* Top level list item 2
  * Nested List item 1
  * Nested List item 2
    * Sub-Nested List item 1
    * Sub-Nested List item 2

<!-- Output with Prettier 1.13 -->
- Top level list item 1
- Top level list item 2
  - Nested List item 1
  - Nested List item 2
    - Sub-Nested List item 1
    - Sub-Nested List item 2

Preserve Liquid tag contents (#4484 by @duailibe)

Liquid is a templating language popular among static site generators such as Jekyll. In Prettier 1.12 and earlier, Liquid tags in markdown files were not properly handled, because Prettier thought they were just text. This would sometimes alter the contents of the tags, changing their meaning. Now Prettier 1.13 understands Liquid tags and will not change their contents.

<!-- Input -->
{% include_relative _installations/tarball.md %}

{% cloudinary nice_prefix_-_for_the_filename.jpg %}

<!-- Output with Prettier 1.12 -->
{% include_relative \_installations/tarball.md %}

{% cloudinary nice*prefix*-\_for_the_filename.jpg %}

<!-- Output with Prettier 1.13 -->
{% include_relative _installations/tarball.md %}

{% cloudinary nice_prefix_-_for_the_filename.jpg %}

Link definitions will be broken onto multiple lines when used with --prose-wrap always if they exceed the print width.

<!-- Input -->
[just-url]: https://example.com
[url-with-short-title]: https://example.com "title"
[url-with-long-title]: https://example.com "a long, long title. It's really really long. Here have words."

[long]: https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx
[long-with-title]: https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx "look a title!"

<!-- Output with Prettier 1.12 -->
[just-url]: https://example.com
[url-with-short-title]: https://example.com "title"
[url-with-long-title]: https://example.com "a long, long title. It's really really long. Here have words."
[long]: https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx
[long-with-title]: https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx "look a title!"

<!-- Output with Prettier 1.13 -->
[just-url]: https://example.com
[url-with-short-title]: https://example.com "title"
[url-with-long-title]:
  https://example.com
  "a long, long title. It's really really long. Here have words."
[long]:
  https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx
[long-with-title]:
  https://example.com/a-long-url/another-segment/yet-another-segment/a-really-long-file-name.php.aspx
  "look a title!"

GraphQL

Only add blank lines after top-level definitions if present in the original source (#4512 by @ad1992)

In Prettier 1.12 and earlier, we would always print a blank line between top level definitions. In 1.13, we would only output a blank line if it was there originally. This behavior is similar to how Prettier formats JavaScript.

# Input
type TypeA {
  fieldA: string
}
type TypeB {
  fieldB: string
}

type TypeC {
  fieldC: string
}

# Output with Prettier 1.12.1
type TypeA {
  fieldA: string
}

type TypeB {
  fieldB: string
}

type TypeC {
  fieldC: string
}

# Output with Prettier 1.13
type TypeA {
  fieldA: string
}
type TypeB {
  fieldB: string
}

type TypeC {
  fieldC: string
}

Other changes

API/CLI

Don't format range if required pragma is missing in the file (#3996 by @josephfrazier)

In Prettier 1.12 and earlier, if a file didn't have a /** @prettier */ pragma and Prettier was called only for a range with --require-pragma, it would format it anyway. Now Prettier will check if the file has the pragma even when only formatting a range.

Improve plugin resolution when path does not start with ./ (#4451 by @kachkaev)

When passing --plugin=path/to/plugin Prettier 1.12 and earlier would crash because it looked for a path/to/plugin in node_modules folder. Prettier 1.13 will look in the current directory first and failing that will look in node_modules.

Adding plugin interface for isBlockComment (#4347 by @mgrip)

A block comment is a comment that can be printed inline (for JS, it's /* comment */) with code. Since Prettier is responsible for printing comments we needed to let plugins determine if a comment is a block comment. Read more in our docs.

JavaScript

Apply destructuring rules in functions to catch param (#4385 by @duailibe)

In 1.12 we formatted destructuring in catch arguments like destructuring in assignments, but the code looks better if we treat it like destructuring in function parameters instead, so we made that change:

// Input
try {
  doSomething();
} catch ({data: {message}}) {
  handleError(message.errors);
}

try {
  doSomething();
} catch ({data: {message: {errors}}}) {
  handleError(errors);
}

// Output with Prettier 1.12.1
try {
  doSomething();
} catch ({
  data: { message }
}) {
  handleError(message.errors);
}

try {
  doSomething();
} catch ({
  data: {
    message: { errors }
  }
}) {
  handleError(errors);
}

// Output with Prettier 1.13
try {
  doSomething();
} catch ({ data: { message } }) {
  handleError(message.errors);
}

try {
  doSomething();
} catch ({
  data: {
    message: { errors }
  }
}) {
  handleError(errors);
}

Escape backslashes correctly for Markdown in JS (#4381 by @ikatyang)

Prettier 1.12 and earlier was incorrectly removing backslashes in Markdown template literals in some cases. Prettier 1.13 will print them correctly.

// Input
markdown`
  const cssString = css\`
    background-color: \$\{color('base')\}
  \`;
`
// Output with Prettier 1.12.1
markdown`
  const cssString = css\`background-color: ${color('base')}\`;
`;

// Output with Prettier 1.13
markdown`
  const cssString = css\`background-color: \$\{color('base')\}\`;
`;

Support styled-components Foo.extend.attrs()`` (#4434 by @duailibe)

In Prettier 1.12.1, Prettier did not detect that the template literal passed to the styled-components function Foo.extends.attrs() was CSS. In 1.13, Prettier now supports this syntax and will format the contents of the template literal as CSS.

// Input
Button.extend.attrs({})`
border-color : black;
`;

// Output with Prettier 1.12
Button.extend.attrs({})`
border-color : black;
`;

// Output with Prettier 1.13
Button.extend.attrs({})`
  border-color: black;
`;

Added support for the GraphQL comment tag (#4395 by @tjallingt)

We format GraphQL in tagged template literals but there are GraphQL libraries that use untagged template literals. Many GraphQL editor plugins have settled on using the comment /* GraphQL */ before an untagged template literal to detect GraphQL. In 1.13, Prettier now also detects that comment and formats the GraphQL code.

// Input
const query = /* GraphQL */`
      {
    user(   id :   5  )  {
      firstName
      lastName
    }
  }
`;

// Output with Prettier 1.13
const query = /* GraphQL */ `
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`;

Format Angular Component styles (#4361 by @JamesHenry)

Prettier 1.13 formats the inline styles of Angular components.

// Input
@Component({
       selector: 'app-test',
  styles: [   `

 :host {
   color: red;
 }
 div { background: blue
 }
`

]
})
class     TestComponent {}

// Output with Prettier 1.13
@Component({
  selector: "app-test",
  styles: [
    `
      :host {
        color: red;
      }
      div {
        background: blue;
      }
    `,
  ],
})
class TestComponent {

Correctly break class property initializers (#4442 by @nicolo-ribaudo)

Prettier 1.12 did not indent the following lines when breaking a class property initializer. This is now fixed in 1.13.

// Input
class Something {
  someInstanceProperty = this.props.foofoofoofoofoofoo &&
  	this.props.barbarbarbar;
}

// Output with Prettier 1.12
class Something {
  someInstanceProperty = this.props.foofoofoofoofoofoo &&
  this.props.barbarbarbar;
}

// Output with Prettier 1.13
class Something {
  someInstanceProperty = this.props.foofoofoofoofoofoo &&
  	this.props.barbarbarbar;
}

Fix long name method in bind expressions (#4447 by @misoguy)

Prettier 1.13 improves formatting of long member expression chains in a bind expression.

// Input
function Foo() {
	const longVariableName = ::veryLongObjectName.veryLongObjectChain.veryLongObjectProperty;
}

// Output with Prettier 1.12
function Foo() {
  const longVariableName = ::veryLongObjectName.veryLongObjectChain
    .veryLongObjectProperty;
}

// Output with Prettier 1.13
function Foo() {
  const longVariableName =
    ::veryLongObjectName.veryLongObjectChain.veryLongObjectProperty;
}

Stop removing parens for the ?. operator (#4542 by @duailibe)

There's an edge case in the optional chaining proposal that wrapping in parens has a difference in the runtime behavior. Prettier 1.12 and earlier were removing the parens in that case, which is now fixed in 1.13.

// Input
(a?.b).c

// Output with Prettier 1.12
a?.b.c

// Output with Prettier 1.13
(a?.b).c

Flow

Wrap ?() => T in parens when needed. (#4475 by @nicolo-ribaudo)

Prettier 1.12 and earlier unintentionally changed the meaning of types when using nullable operator because of the precedence of operators. This is now fixed in Prettier 1.13.

// Input
type Foo = { arg: ?(() => void) | string };

// Output with Prettier 1.12
type Foo = { arg: ?() => void | string };
// which is equivalent to:
type Foo = { arg: ?() => (void | string) };

// Output with Prettier 1.13
type Foo = { arg: ?(() => void) | string };

TypeScript

Preserve quoted class properties (#4517 by @ikatyang)

Strict property initialization checks are not applied to quoted class properties in TypeScript. In Prettier 1.13 we'll preserve the quotes if they were originally in the code.

// Input
class Username {
  age: number;
  "username": string;
}

// Output with Prettier 1.12
class Username {
  age: number;
  username: string;
}

// Output with Prettier 1.13
class Username {
  age: number;
  "username": string;
}

Markdown

Remove newline in empty .md files (#4388 by @huyvohcmc)

In Prettier 1.12.1, a newline would be printed when formatting an empty markdown file. This is now fixed in 1.13.

Prevent merge continuous CJK text with --prose-wrap preserve (#4504 by @ikatyang)

When using --prose-wrap preserve, Prettier will no longer merge continuous CJK text broken across multiple lines.

<!-- Input -->
::: warning 注意
该网站在国外无法访问,故以下演示无效
:::

<!-- Output with Prettier 1.12 -->
::: warning 注意该网站在国外无法访问,故以下演示无效
:::

<!-- Output with Prettier 1.13 -->
::: warning 注意
该网站在国外无法访问,故以下演示无效
:::

CSS/SCSS/Less

Print trailing commas in SCSS list and maps (#4317 by @ad1992)

Prettier now prints trailing commas in lists and maps in SCSS if trailingComma is not "none" and the list or map is broken onto multiple lines.

/* Input */
$list: (a);
$colors: (
  "red",
  "blue"
);
$map: (
  'medium': (min-width: 800px),
  'large': (min-width: 1000px),
  'huge': (min-width: 1200px),
);

/* Output with Prettier 1.13 */
$list: (a);
$colors: (
  "red",
  "blue",
);
$map: (
  "medium": (min-width: 800px),
  "large": (min-width: 1000px),
  "huge": (min-width: 1200px),
);

Fix empty front-matter (#4392 and #4457 by @eliasmeire)

Prettier 1.12 was released with support for front-matter blocks in CSS/SCSS/Less files, but it was removing empty blocks (or blocks with only comments). This is now fixed in 1.13.

Don't format SCSS string interpolation (#4490 by @evilebottnawi)

Prettier would break SCSS code when formatting a string with interpolation for some cases. Prettier 1.13 will print the original code.

/* Input
a {
 content: "#{my-fn("_")}";
}

/* Output with Prettier 1.12 */
a {
 content: "#{my-fn(" _ ")}";
}

/* Output with Prettier 1.13 */
a {
 content: "#{my-fn("_")}";
}

Escape characters correctly (#4472 by @evilebottnawi)

Prettier 1.12 would not escape characters correctly in some cases.

/* Input */
@media only screen and (max-width: 767px) {
    @include widths(2 3 4, \@small);
}

$widths-breakpoint-separator: \@small;

/* Output with Prettier 1.12 */
@media only screen and (max-width: 767px) {
  @include widths(2 3 4, \ @small);
}

$widths-breakpoint-separator: \ @small;

/* Output with Prettier 1.13 */
@media only screen and (max-width: 767px) {
    @include widths(2 3 4, \@small);
}

$widths-breakpoint-separator: \@small;

Fix SCSS interpolation in CSS variables (#4471 by @evilebottnawi)

/* Input */
a {
  --bg: var(--#{$type});
}

/* Output with Prettier 1.12 */
a {
  --bg: var(-- #{$type});
}

/* Output with Prettier 1.13 */
a {
  --bg: var(--#{$type});
}

Fix spacing issue in PostCSS computed variables (#4408 by @ad1992)

/* Input */
background-color: $$(style)Color;

/* Output with Prettier 1.12 */
background-color: $$(style) Color;

/* Output with Prettier 1.13 */
background-color: $$(style)Color;