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
The aspect main runtime (e.g, my-formatter.main.ts) should have the following methods:
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); }
The formatter should know to handle both - format in workspace and for build
The formatter implementation uses the formatter extension as a convention. For example, my-formatter.formatter.ts.
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>;
check
Run the formatter but do not change the files on the file system
check(context: FormatterContext): Promise<FormatResults>;
The formatterContext contains the regular ExecutionContext and the formatterOptions.
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, };
Formatting during build will soon be available.