Files
test-repo/changelog_unreleased/api/16567.md
T

1.8 KiB

Make getPreferredQuote public (#16567 by @sosukesuzuki)

This change makes the internal getPreferredQuote function a part of the public API.

In languages like JavaScript, both single quotes and double quotes can be used for string literals. Prettier determines the quote to enclose a string literal based on the number of quotes within the string and the value of the singleQuote option. For more details, please refer to the Rationale page.

The getPreferredQuote function determines the appropriate quote to enclose a string literal and has the following interface:

type Quote = '"' | "'";
function getPreferredQuote(
  text: string,
  preferredQuoteOrPreferSingleQuote: Quote | boolean,
): Quote;

Here are some examples of how to use it:

import * as prettier from "prettier";

const SINGLE_QUOTE = `'`;
const DOUBLE_QUOTE = `"`;

console.log(prettier.util.getPreferredQuote(`Hello World Test`, SINGLE_QUOTE)); // '
console.log(prettier.util.getPreferredQuote(`Hello World Test`, DOUBLE_QUOTE)); // "
console.log(prettier.util.getPreferredQuote(`'Hello' "World" 'Test'`, SINGLE_QUOTE)); // "
console.log(prettier.util.getPreferredQuote(`"Hello" 'World' "Test"`, DOUBLE_QUOTE)); // '
console.log(prettier.util.getPreferredQuote(`"Hello" "World" "Test"`, SINGLE_QUOTE)); // '
console.log(prettier.util.getPreferredQuote(`'Hello' 'World' 'Test'`, DOUBLE_QUOTE)); // "

Making this function public will benefit plugin developers. Since the function is relatively short, you can find more details in the implementation.