Implement a Formatter

Standard formatter like Prettier are integrated into Bit using a Bit Aspect . For example, the Prettier Aspect. These Aspects implement the Formatter's interface.

The easiest way to start implementing a Formatter is to create a new Bit Aspect using the Aspect template:

bit create aspect extensions/my-formatter
CopiedCopy

Main runtime file

The aspect main runtime (e.g, my-formatter.main.ts) should have the following methods:

createFormatter

Create an instance of a class that should implement the Formatter interface. This is usually implemented in a file called <formatter-name>.formatter.ts

/**
 * create a prettier formatter instance.
 * @param options prettier options.
 * @param PrettierModule reference to an `prettier` module.
 */
createFormatter(
  context: FormatterContext,
  options: PrettierOptions,
  transformers: PrettierConfigTransformer[] = [],
  PrettierModule?: any
): Formatter {
  const configMutator = new PrettierConfigMutator(options.config);
  const transformerContext: PrettierConfigTransformContext = { check: !!context.check };
  const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);
  return new PrettierFormatter(this.logger, afterMutation.raw, PrettierModule);
}
CopiedCopy

The formatter should know to handle both - format in workspace and for build

Implementation file

The formatter implementation uses the formatter extension as a convention. For example, my-formatter.formatter.ts.

Linting in the Workspace

The formatter should implement format and check methods.

format

Run the formatter and change the files on the file system

format(context: FormatterContext): Promise<FormatResults>;
CopiedCopy

check

Run the formatter but do not change the files on the file system

check(context: FormatterContext): Promise<FormatResults>;
CopiedCopy

The formatterContext contains the regular ExecutionContext and the formatterOptions.

FormatResults

type FormatResults = {
  results: ComponentFormatResult[],
  errors: Error[],
};

type ComponentFormatResult = {
  /**
   * the formatted component.
   */
  component: Component,

  results: FileFormatResult[],
};

type FileFormatResult = {
  /**
   * path of the formatted file.
   */
  filePath: string,

  /**
   * Does the file has formatting issues (needs format)
   */
  hasIssues: boolean,

  /**
   * The new file content after the formatting
   */
  newContent?: string,
};
CopiedCopy

Formatting during build

Formatting during build will soon be available.