Skip to content

About

A configurable Prettier plugin to format embedded languages in JS/TS Files.

Topics

Resources

Contributing

Stars

84 stars

Watchers

1 watching

Forks

Latest commit

Β 

History

204 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

prettier-plugin-embed-wide-logo prettier-plugin-embed-wide-logo

Prettier Plugin Embed

npm version npm downloads npm license All Contributors

github last commit bundlephobia minzipped

A configurable Prettier plugin to format embedded languages in JS/TS Files.

npm i -D prettier prettier-plugin-embed

Introduction

What?

This Prettier plugin formats embedded languages in template literals within JavaScript and TypeScript files.

Why?

It adds per-language formatting controls, configurable block comments and tags, and per-identifier overrides to Prettier's embedded formatting. See prettier/prettier#4424 and prettier/prettier#5588 for related use cases.

How?

The plugin extends the embed method of Prettier's estree printer. Each integration delegates formatting to Prettier or a loaded language plugin. See the printer implementation for the integration point.

Features

  • Support for Additional Languages: Extend embedded formatting to languages such as XML, SQL, PHP, and more. See Language-Specific Options for the supported languages and their default identifiers.

  • Dual Identification Modes: Identify embedded languages by block comments /* comment */ `...` or tags tag`...` preceding the template literals.

  • Customizable Language Comments or Tags: Customize the comments or tags used for identifying the embedded languages.

  • Formatting Opt-out Mechanism: Offer the capability to deactivate formatting for certain comments or tags, including the built-in ones (html, css...) supported by the embedded-language-formatting option.

  • Configurable Formatting Style: Provide additional options to tailor the formatting style for embedded languages.

  • Strongly Typed API: Benefit from comprehensive type support for configuring this plugin's options.

  • Easy Integration: Integrate with the existing Prettier setup seamlessly, requiring minimal configuration to get started.

Installation

npm i -D prettier prettier-plugin-embed

Install Prettier 3 in the project that runs formatting. The consumer supplies the formatter and its language plugins.

Install the formatter plugin for each embedded language you use as a separate project dependency; the Language-Specific Options section shows which integrations require one.

Choose Prettier and runtime versions supported by every loaded language plugin. Parser availability and syntax support follow the installed formatter version.

Dependency resolution in strict installations

The plugin loads Prettier through static imports, which resolve from the plugin's installation location. Standard project installs and Yarn's default Plug'n'Play dependency fallback allow these imports to access the project's installed Prettier.

Yarn projects using pnpFallbackMode: none, and pnpm projects using enableGlobalVirtualStore: true with hoisting disabled, need an explicit dependency relationship for this resolution. For these configurations, add the following to .yarnrc.yml (Yarn) or pnpm-workspace.yaml (pnpm) to connect the plugin to the project's installed Prettier:

packageExtensions:
  "prettier-plugin-embed@*":
    peerDependencies:
      prettier: ">=3.0.0 <4"

Projects can also use Yarn's default pnpFallbackMode: dependencies-only or pnpm's project-local virtual store (enableGlobalVirtualStore: false).

Usage

Getting Started

This is a Prettier plugin, which follows the standard usage pattern of many other Prettier plugins:

Via --plugin:

prettier --write main.ts --plugin=prettier-plugin-embed

Via the plugins options:

await prettier.format(code, {
  filepath: "main.ts",
  plugins: ["prettier-plugin-embed"],
});
{
  "plugins": ["prettier-plugin-embed"]
}

For Yarn Plug'n'Play, load plugin objects from a JavaScript config so the imports resolve through Yarn's dependency map.

import * as prettierPluginEmbed from "prettier-plugin-embed";

export default {
  plugins: [prettierPluginEmbed],
};

Quick Start Config Examples

See Config Examples for complete language plugin configurations and sample output.

An Overview of the Philosophy

Set embeddedLanguageFormatting to "auto" (Prettier's default) to enable embedded formatting.

This plugin uses Prettier's built-in parsers and existing language plugins, adding the integration needed to format their languages inside template literals.

Install and load the formatter plugin for each additional language you use. For example, embedded XML requires both this plugin and @prettier/plugin-xml. The Language-Specific Options section lists the required plugins.

A preceding block comment such as /* xml */ `...` or a tag such as xml`...` identifies the embedded language. Configure each language with embedded<Language>Comments and embedded<Language>Tags. A leading block comment is checked first; templates without one are matched by their tag.

Tags support exact identifiers, member expressions, and regular expression strings in /pattern/flags form. Simple identifiers support patterns too: "/^query$/" matches the tag query. Member and call expressions use a normalized form for pattern matching; for example, factory(argument).query becomes factory().query.

For example, this JSON configuration matches prisma.$queryRaw, client.$queryRaw, and ctx.prisma.$queryRaw. JSON and JavaScript strings escape each backslash as \\:

{
  "plugins": ["prettier-plugin-embed", "prettier-plugin-sql"],
  "embeddedSqlTags": ["/\\.\\$queryRaw$/"]
}

Add comments or tags to embeddedNoopComments or embeddedNoopTags to preserve their template content as written. These options take priority among matching languages. Other overlapping matches use the first matching language in the internal registry; assign distinct identifiers or non-overlapping patterns to select a language explicitly.

Important

Specify comments or tags explicitly to keep language identification stable across plugin versions.

Language-Specific Options

Supported embedded languages and their default comment/tag identifiers are:

Click Here to Toggle

NOOP

embeddedNoopComments
  • Type: string[]
  • Default: []
  • Description: Block comments that prevent their subsequent template literals from being identified as embedded languages and thus from being formatted.
embeddedNoopTags
  • Type: string[]
  • Default: []
  • Description: Tags that prevent their subsequent template literals from being identified as embedded languages and thus from being formatted.

This built-in option can override native embedded language formatting for the specified comments or tags, preserving their template literal content as written.

Astro

embeddedAstroComments
  • Type: string[]
  • Default: ["astro"]
  • Description: Block comments that identify embedded Astro in template literals. Requires the prettier-plugin-astro plugin.
embeddedAstroTags

Formatting embedded Astro requires the prettier-plugin-astro plugin to be installed and loaded. Its options control the embedded formatting behavior.

CSS

embeddedCssComments
  • Type: string[]
  • Default: ["css"]
  • Description: Block comments that make their subsequent template literals be identified as embedded CSS language.
embeddedCssTags
  • Type: string[]
  • Default: ["css"]
  • Description: Tags that make their subsequent template literals be identified as embedded CSS language.
embeddedCssParser

Embedded CSS uses the parsers and printers included with Prettier.

This can override the native formatting behavior for embedded CSS language. If you want to keep the native behavior, set embeddedCssComments or embeddedCssTags to [] or other values.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

Dockerfile

embeddedDockerfileComments
embeddedDockerfileTags

Formatting embedded Dockerfile requires the prettier-plugin-sh plugin to be installed and loaded. Its options control the embedded formatting behavior.

Dockerfile and Shell share prettier-plugin-sh; the Dockerfile integration selects its dockerfile parser.

ES (ECMAScript/JavaScript)

embeddedEsComments
embeddedEsTags
embeddedEsParser

Embedded ECMAScript and JavaScript use the parsers and printers included with Prettier.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

Gherkin

embeddedGherkinComments
embeddedGherkinTags

Formatting embedded Gherkin requires the prettier-plugin-gherkin plugin to be installed and loaded. Its options control the embedded formatting behavior.

GLSL

embeddedGlslComments
  • Type: string[]
  • Default: ["glsl", "shader"]
  • Description: Block comments that make their subsequent template literals be identified as embedded GLSL language. This option requires the prettier-plugin-glsl plugin.
embeddedGlslTags
  • Type: string[]
  • Default: ["glsl", "shader"]
  • Description: Tags that make their subsequent template literals be identified as embedded GLSL language. This option requires the prettier-plugin-glsl plugin.

Formatting embedded GLSL language requires the prettier-plugin-glsl plugin to be loaded as well.

Go Template

embeddedGoTemplateComments
embeddedGoTemplateTags

Formatting embedded Go Template requires the @htnabe/prettier-plugin-go-template plugin to be installed and loaded. Its options control the embedded formatting behavior.

GraphQL

embeddedGraphqlComments
  • Type: string[]
  • Default: ["graphql", "gql"]
  • Description: Block comments that make their subsequent template literals be identified as embedded GraphQL language.
embeddedGraphqlTags
  • Type: string[]
  • Default: ["graphql", "gql"]
  • Description: Tags that make their subsequent template literals be identified as embedded GraphQL language.

Embedded GraphQL uses the parsers and printers included with Prettier.

This can override the native formatting behavior for embedded GraphQL language. If you want to keep the native behavior, set embeddedGraphqlComments or embeddedGraphqlTags to [] or other values.

Handlebars

embeddedHandlebarsComments
embeddedHandlebarsTags

Formatting embedded Handlebars requires the @poliklot/prettier-plugin-handlebars plugin to be installed and loaded. Its options control the embedded formatting behavior.

HTML

embeddedHtmlComments
  • Type: string[]
  • Default: ["html", "xhtml"]
  • Description: Block comments that make their subsequent template literals be identified as embedded HTML language.
embeddedHtmlTags
  • Type: string[]
  • Default: ["html", "xhtml"]
  • Description: Tags that make their subsequent template literals be identified as embedded HTML language.
embeddedHtmlParser

Embedded HTML uses the parsers and printers included with Prettier.

This can override the native formatting behavior for embedded HTML language. If you want to keep the native behavior, set embeddedHtmlComments or embeddedHtmlTags to [] or other values.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

Hugo

embeddedHugoComments
embeddedHugoTags

Formatting embedded Hugo requires the @htnabe/prettier-plugin-hugo-post plugin to be installed and loaded. Its options control the embedded formatting behavior.

INI

embeddedIniComments
  • Type: string[]
  • Default: ["ini", "cfg", "pro"]
  • Description: Block comments that make their subsequent template literals be identified as embedded INI language. This option requires the prettier-plugin-ini plugin.
embeddedIniTags
  • Type: string[]
  • Default: ["ini", "cfg", "pro"]
  • Description: Tags that make their subsequent template literals be identified as embedded INI language. This option requires the prettier-plugin-ini plugin.

Formatting embedded INI language requires the prettier-plugin-ini plugin to be loaded as well. And options supported by prettier-plugin-ini can therefore be used to further control the formatting behavior.

Java

embeddedJavaComments
  • Type: string[]
  • Default: ["java"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Java language. This option requires the prettier-plugin-java plugin.
embeddedJavaTags
  • Type: string[]
  • Default: ["java"]
  • Description: Tags that make their subsequent template literals be identified as embedded Java language. This option requires the prettier-plugin-java plugin.

Formatting embedded Java language requires the prettier-plugin-java plugin to be loaded as well. And options supported by prettier-plugin-java can therefore be used to further control the formatting behavior.

Jinja

embeddedJinjaComments
embeddedJinjaTags

Formatting embedded Jinja requires the prettier-plugin-jinja-template plugin to be installed and loaded. Its options control the embedded formatting behavior.

The formatter uses the source block's line breaks to choose its layout. Write block bodies across lines for consistent formatting when their content wraps.

JSON

embeddedJsonComments
  • Type: string[]
  • Default: ["json", "jsonl"]
  • Description: Block comments that make their subsequent template literals be identified as embedded JSON language.
embeddedJsonTags
  • Type: string[]
  • Default: ["json", "jsonl"]
  • Description: Tags that make their subsequent template literals be identified as embedded JSON language.
embeddedJsonParser

Embedded JSON uses the parsers and printers included with Prettier.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

JSONata

embeddedJsonataComments
  • Type: string[]
  • Default: ["jsonata"]
  • Description: Block comments that make their subsequent template literals be identified as embedded JSONata language. This option requires the @stedi/prettier-plugin-jsonata plugin.
embeddedJsonataTags
  • Type: string[]
  • Default: ["jsonata"]
  • Description: Tags that make their subsequent template literals be identified as embedded JSONata language. This option requires the @stedi/prettier-plugin-jsonata plugin.

Formatting embedded JSONata language requires the @stedi/prettier-plugin-jsonata plugin to be loaded as well.

JTE

embeddedJteComments
  • Type: string[]
  • Default: ["jte"]
  • Description: Block comments that identify embedded JTE in template literals. Requires the prettier-plugin-jte plugin.
embeddedJteTags
  • Type: string[]
  • Default: ["jte"]
  • Description: Tags that identify embedded JTE in template literals. Requires the prettier-plugin-jte plugin.

Formatting embedded JTE requires the prettier-plugin-jte plugin to be installed and loaded. Its options control the embedded formatting behavior.

LaTeX

embeddedLatexComments
embeddedLatexTags

Formatting embedded LaTeX language requires the prettier-plugin-latex plugin to be loaded as well.

Liquid

embeddedLiquidComments
embeddedLiquidTags

Formatting embedded Liquid requires the @shopify/prettier-plugin-liquid plugin to be installed and loaded. Its options control the embedded formatting behavior.

Markdown

embeddedMarkdownComments
  • Type: string[]
  • Default: ["md", "markdown"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Markdown language.
embeddedMarkdownTags
  • Type: string[]
  • Default: ["md", "markdown"]
  • Description: Tags that make their subsequent template literals be identified as embedded Markdown language.
embeddedMarkdownParser

Embedded Markdown uses the parsers and printers included with Prettier.

This can override the native formatting for embedded Markdown language. If you want to keep the native behavior, set embeddedMarkdownComments or embeddedMarkdownTags to [] or other values.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

The remark parser is an alias of the markdown parser.

Marko

embeddedMarkoComments
  • Type: string[]
  • Default: ["marko"]
  • Description: Block comments that identify embedded Marko in template literals. Requires the prettier-plugin-marko plugin.
embeddedMarkoTags

Formatting embedded Marko requires the prettier-plugin-marko plugin to be installed and loaded. Its options control the embedded formatting behavior.

Motoko

embeddedMotokoComments
embeddedMotokoTags

Formatting embedded Motoko requires the prettier-plugin-motoko plugin to be installed and loaded. Its options control the embedded formatting behavior.

Mustache

embeddedMustacheComments
embeddedMustacheTags

Formatting embedded Mustache requires the prettier-plugin-mustache plugin to be installed and loaded. Its options control the embedded formatting behavior.

NGINX

embeddedNginxComments
  • Type: string[]
  • Default: ["nginx"]
  • Description: Block comments that make their subsequent template literals be identified as embedded NGINX language. This option requires the prettier-plugin-nginx plugin.
embeddedNginxTags
  • Type: string[]
  • Default: ["nginx"]
  • Description: Tags that make their subsequent template literals be identified as embedded NGINX language. This option requires the prettier-plugin-nginx plugin.

Formatting embedded NGINX language requires the prettier-plugin-nginx plugin to be loaded as well. And options supported by prettier-plugin-nginx can therefore be used to further control the formatting behavior.

Nunjucks

embeddedNunjucksComments
embeddedNunjucksTags

Formatting embedded Nunjucks requires the prettier-plugin-nunjucks plugin to be installed and loaded. Its options control the embedded formatting behavior.

Pegjs

embeddedPegjsComments
embeddedPegjsTags

Formatting embedded Pegjs language requires the prettier-plugin-pegjs plugin to be loaded as well. And options supported by prettier-plugin-pegjs can therefore be used to further control the formatting behavior.

Note that prettier-plugin-pegjs supports different parsers for the action blocks and they are specified by the actionParser option. If you want to specify different action parsers for different comments or tags, check embeddedOverrides.

PHP

embeddedPhpComments
  • Type: string[]
  • Default: ["php", "php5"]
  • Description: Block comments that make their subsequent template literals be identified as embedded PHP language. This option requires the @prettier/plugin-php plugin.
embeddedPhpTags
  • Type: string[]
  • Default: ["php", "php5"]
  • Description: Tags that make their subsequent template literals be identified as embedded PHP language. This option requires the @prettier/plugin-php plugin.

Formatting embedded PHP language requires the @prettier/plugin-php plugin to be loaded as well. And options supported by @prettier/plugin-php can therefore be used to further control the formatting behavior.

PowerShell

embeddedPowerShellComments
embeddedPowerShellTags

Formatting embedded PowerShell requires the prettier-plugin-powershell plugin to be installed and loaded. Its options control the embedded formatting behavior.

Prisma

embeddedPrismaComments
  • Type: string[]
  • Default: ["prisma"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Prisma language. This option requires the prettier-plugin-prisma plugin.
embeddedPrismaTags
  • Type: string[]
  • Default: ["prisma"]
  • Description: Tags that make their subsequent template literals be identified as embedded Prisma language. This option requires the prettier-plugin-prisma plugin.

Formatting embedded Prisma language requires the prettier-plugin-prisma plugin to be loaded as well.

Properties

embeddedPropertiesComments
  • Type: string[]
  • Default: ["properties"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Properties language. This option requires the prettier-plugin-properties plugin.
embeddedPropertiesTags
  • Type: string[]
  • Default: ["properties"]
  • Description: Tags that make their subsequent template literals be identified as embedded Properties language. This option requires the prettier-plugin-properties plugin.

Formatting embedded Properties language requires the prettier-plugin-properties plugin to be loaded as well. And options supported by prettier-plugin-properties can therefore be used to further control the formatting behavior.

Pug

embeddedPugComments
  • Type: string[]
  • Default: ["pug", "jade"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Pug language. This option requires the @prettier/plugin-pug plugin.
embeddedPugTags
  • Type: string[]
  • Default: ["pug", "jade"]
  • Description: Tags that make their subsequent template literals be identified as embedded Pug language. This option requires the @prettier/plugin-pug plugin.

Formatting embedded Pug language requires the @prettier/plugin-pug plugin to be loaded as well. And options supported by @prettier/plugin-pug can therefore be used to further control the formatting behavior.

Ruby

embeddedRubyComments
  • Type: string[]
  • Default: ["ruby"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Ruby language. This option requires the @prettier/plugin-ruby plugin.
embeddedRubyTags
  • Type: string[]
  • Default: ["ruby"]
  • Description: Tags that make their subsequent template literals be identified as embedded Ruby language. This option requires the @prettier/plugin-ruby plugin.
embeddedRubyParser

Formatting embedded Ruby language requires the @prettier/plugin-ruby to be loaded and its dependencies to be installed as well. And options supported by @prettier/plugin-ruby can therefore be used to further control the formatting behavior.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

Sh (Shell)

embeddedShComments
  • Type: string[]
  • Default: ["sh"]
  • Description: Block comments that make their subsequent template literals be identified as embedded Shell language. This option requires the prettier-plugin-sh plugin.
embeddedShTags
  • Type: string[]
  • Default: ["sh"]
  • Description: Tags that make their subsequent template literals be identified as embedded Shell language. This option requires the prettier-plugin-sh plugin.

Formatting embedded Shell language requires the prettier-plugin-sh plugin to be loaded as well. And options supported by prettier-plugin-sh can therefore be used to further control the formatting behavior.

Note that prettier-plugin-sh supports different variants of shell syntaxes and they are specified by the variant option. If you want to specify different variants for different comments or tags, check embeddedOverrides.

Solidity

embeddedSolidityComments
embeddedSolidityTags
embeddedSolidityParser

Formatting embedded Solidity requires the prettier-plugin-solidity plugin to be installed and loaded. Its options control the embedded formatting behavior.

Choose "slang" or "antlr" with current formatter versions. Formatter versions exposing "solidity-parse" use embeddedSolidityParser: "solidity-parse".

SQL

embeddedSqlComments
embeddedSqlTags
embeddedSqlPlugin
embeddedSqlParser

Formatting embedded SQL language requires the prettier-plugin-sql plugin or the prettier-plugin-sql-cst plugin to be loaded as well. And options supported by prettier-plugin-sql, or options supported by prettier-plugin-sql-cst can therefore be used to further control the formatting behavior.

Note that prettier-plugin-sql supports many different SQL dialects which are specified by the language, database or dialect option. And prettier-plugin-sql-cst also supports various parsers as shown above. If you want to specify different dialects or parsers for different comments or tags, check embeddedOverrides.

Svelte

embeddedSvelteComments
  • Type: string[]
  • Default: ["svelte"]
  • Description: Block comments that identify embedded Svelte in template literals. Requires the prettier-plugin-svelte plugin.
embeddedSvelteTags

Formatting embedded Svelte requires the prettier-plugin-svelte plugin to be installed and loaded. Its options control the embedded formatting behavior.

Supply the svelte compiler alongside the formatter plugin, using versions compatible with the project's Svelte version.

TOML

embeddedTomlComments
  • Type: string[]
  • Default: ["toml"]
  • Description: Block comments that make their subsequent template literals be identified as embedded TOML language. This option requires the prettier-plugin-toml plugin.
embeddedTomlTags
  • Type: string[]
  • Default: ["toml"]
  • Description: Tags that make their subsequent template literals be identified as embedded TOML language. This option requires the prettier-plugin-toml plugin.

Formatting embedded TOML language requires the prettier-plugin-toml plugin to be loaded as well. And options supported by prettier-plugin-toml can therefore be used to further control the formatting behavior.

TS (TypeScript)

embeddedTsComments
embeddedTsTags
embeddedTsParser

Embedded TypeScript uses the parsers and printers included with Prettier.

If you want to specify different parsers for different comments or tags, check embeddedOverrides.

XML

embeddedXmlComments
embeddedXmlTags

Embedded XML uses the parser provided by @prettier/plugin-xml, which must be loaded when XML formatting is enabled. Its options control the XML formatting behavior.

XQuery

embeddedXQueryComments
embeddedXQueryTags
embeddedXQueryParser

Formatting embedded XQuery requires the prettier-plugin-xquery plugin to be installed and loaded. Its options control the embedded formatting behavior.

The default "xquery" parser formats XQuery 3.1. Select "xquery4" for the XQuery 4 syntax supported by the installed formatter version.

YAML

embeddedYamlComments
  • Type: string[]
  • Default: ["yaml", "yml"]
  • Description: Block comments that make their subsequent template literals be identified as embedded YAML language.
embeddedYamlTags
  • Type: string[]
  • Default: ["yaml", "yml"]
  • Description: Tags that make their subsequent template literals be identified as embedded YAML language.

Embedded YAML uses the parsers and printers included with Prettier.

Language-Agnostic Options

Language-Agnostic

preserveEmbeddedExteriorWhitespaces
  • Type: string[]
  • Default: []
  • Description: Preserves leading and trailing whitespaces in the formatting results for the specified comments or tags.
noEmbeddedMultiLineIndentation
  • Type: string[]
  • Default: []
  • Description: Turns off auto indentation in the formatting results for the specified comments or tags when they are formatted to span multi lines.
embeddedOverrides
  • Type: string
  • Default: undefined
  • Description: Option overrides for the specified comments or tags. It should either be a stringified JSON or an absolute filepath to the option overrides file. See below for a detailed explanation.

embeddedOverrides

This option is provided for users to override certain options based on comments or tags. Due to the lack of support for using objects in prettier plugin options (prettier/prettier#14671), it accepts a stringified json string, or a file path with an extension of .json, .jsonc, .js, .cjs, .mjs, .ts, .cts or .mts as its value. If no extension is provided, it will be treated as a .json/.jsonc file. For relative paths, it will automatically figure out the prettier config location and use that as the base path.

TypeScript override files (.ts, .mts and .cts) are loaded with the active runtime's import(). Node.js with native type stripping enabled can load erasable TypeScript, and Bun provides native TypeScript loading. The runtime determines module semantics: .mts uses ES modules, .cts uses CommonJS, and .ts follows the package's module type.

Consumers can enable a compatible loader through Node.js startup options, such as node --import tsx node_modules/prettier/bin/prettier.cjs . --write. Override files are evaluated in workers, which inherit the runtime's startup preloads. Enable synchronous module hooks through a --import or --require preload so they are available in those workers. When the runtime reports unsupported module loading or TypeScript transformation, the plugin can use the consumer project's optional tsx 4.19+ installation as a fallback. This fallback uses Node.js's module.register() API, introduced in Node.js 18.19 and 20.6. Configuration errors include their original diagnostics.

The Prettier VS Code extension uses its bundled Node.js runtime; JavaScript override files provide the simplest editor setup.

Each override module load uses a fresh worker and module cache, so edits to the override file and its imported modules are reflected in subsequent formatting calls. Workers are released after the configuration has been read. Relative paths follow Prettier's configuration discovery and its clearConfigCache() API.

The resolved value should be an array of objects. Each object in the array must have 2 fields: comments and options, or tags and options. The options are considered overrides that will be applied to the global options of prettier for those comments and tags only. It's like the overrides of prettier, but it is comment/tag-based instead of file-based.

Per-tag overrides refer to the matching entry from embedded<Language>Tags, including the pattern string when a regular expression matches. The first matching override applies. For example, this JavaScript configuration gives embedded JavaScript selected by query its own quote style:

export default {
  plugins: ["prettier-plugin-embed"],
  embeddedEsTags: ["/^query$/"],
  embeddedOverrides: JSON.stringify([
    { tags: ["/^query$/"], options: { singleQuote: true } },
  ]),
};

Embedded parsers receive the override options. The resulting document is laid out with the surrounding JavaScript or TypeScript document, using the outer Prettier printWidth.

In a json file, the root is the array of objects. In a JavaScript/TypeScript file, the array of objects should be a default export, or a named export with the name embeddedOverrides.

An example .json/.jsonc file is:

[
  {
    "comments": ["sql"],
    "options": {
      "keywordCase": "lower"
    }
  },
  {
    "tags": ["mysql"],
    "options": {
      "keywordCase": "upper"
    }
  }
]

Caution

embeddedOverrides supports options applied during parsing and document generation. Options applied during final document printing, such as tabWidth, are configured globally. The EmbeddedOverride interface lists the supported override options.

Typed Options

There're several ways to use the typed options provided by this plugin. Taking the embedded SQL language as an example:

  • Augment the Options type from Prettier to use plugin-specific options

    Register options from prettier-plugin-embed (this plugin):

    /// <reference types="prettier-plugin-embed/plugin-embed" />

    Register options from prettier-plugin-sql:

    /// <reference types="prettier-plugin-embed/embedded/sql/plugin-sql" />

    Other embedded languages share the same pattern:

    /// <reference types="prettier-plugin-embed/embedded/<language>/<(no prettier or scope) plugin name>" />
  • Import plugin-specific options

    Import options from prettier-plugin-embed (this plugin):

    import type { PluginEmbedOptions } from "prettier-plugin-embed";

    Import options from prettier-plugin-sql:

    import type { PluginSqlOptions } from "prettier-plugin-embed/embedded/sql/plugin-sql-types";

    NOTE: You can also import the types from the prettier-plugin-sql plugin directly. However, not all of the plugins provide types, or provide them in a predictable way, so this plugin exports them in a more unified manner.

    Other embedded languages share the same pattern:

    import type { Plugin<Language>Options } from "prettier-plugin-embed/embedded/<language>/<(no prettier or scope) plugin name>-types";
  • Use JSDoc in JavaScript files

    /**
     * @type {import("prettier-plugin-embed").PluginEmbedOptions}
     */
    const pluginEmbedOptions = {
      embeddedSqlTags: ["sql"],
    };
    
    /**
     * @type {import("prettier-plugin-embed/embedded/sql/plugin-sql-types").PluginSqlOptions}
     */
    const pluginSqlOptions = {
      language: "postgresql",
      keywordCase: "upper",
    };

Contributing

Bug fixes, new language support and tests are welcome. Please have a look at the project structure before getting started. Feel free to leave questions or suggestions.

Contributors

Karl Horky
Karl Horky

πŸ’» πŸ“–
Kelvin Soh
Kelvin Soh

πŸ’»
JounQin
JounQin

πŸ’»

License

MIT

About

A configurable Prettier plugin to format embedded languages in JS/TS Files.

Topics

Resources

Contributing

Stars

84 stars

Watchers

1 watching

Forks

Releases

Used by

Contributors

Languages