Create a Formatter

Bit formatters format component source files during the component development and during the component build process. They are often used to integrate popular formatters such as Prettier, JS Beautify and Clang-Format into Bit, but can also be used to implement custom formatters.

Run the following to fork a demo formatter that you can use as a template for your own formatter:

$bit
Copiedcopy

Alternatively, run the following to create a workspace with a formatter, an env that uses the formatter, and a sample component that uses that env (replace my-org.my-scope with your own bit.cloud org/username and scope name):

$bit
Copiedcopy

Run bit format sample-component to format the component using the formatter.

Implement the run method to format component source files during development. The component source files are provided to the formatter via the (FormatterContext). The formatter should return the list of files re-formatted in the workspace.

async run( context: FormatterContext & ExecutionContext ): Promise<FormatResults> {
  const results: ComponentFormatResult[] = [];
  // Loop through each component in parallel
  await Promise.all(
    context.components.map(async (component) => {
      const files: (FileFormatResult | undefined)[] = [];

      await Promise.all(
        component.filesystem.files.map(async (file) => {
          // implement the formatter logic here
          files.push({
            filePath: file.relative,
            hasIssues,
            newContent,
          });
        })
      );

      results.push({
        component,
        results: files.filter(
          (item) => item !== undefined
        ) as FileFormatResult[],
      });
    })
  );

  return {
    results,
    errors: [],
  };
}
CopiedCopy

Additional methods and properties

Method SignatureDescription
displayName: stringShow the display name of the formatter.
displayConfig(): JSONShow the formatter configuration.
version(): stringReturns the formatter version.

Use the formatter

Formatters are used by components via the components' envs. To use your formatter, follow these steps (or use the workspace starter at the top of this page):

  1. Create a new env or use an existing one.
  2. Set the formatter as the env's formatter.
  3. Create a component using that env or set an existing component to use that env.

Test the formatter

Learn about debugging components in the workspace in this blog.

Run the following to format the component during development (in the workspace):

$bit
Copiedcopy

Learn more about running the formatter in the Using formatters page.