CompilerPlugin
A compiler plugin: a build-time function over the tree of one module.
A compiler plugin: a build-time function over the tree of one module. Plugins run in the order of
the list, "pre" plugins before the compiler passes and "post" plugins after code generation.
They are passed as values to compile (plugins) or to the Vite plugin; nothing loads them by
name. A plugin must be deterministic and synchronous.
Import#
ts
import type { CompilerPlugin } from "@shadow-js/compiler";
Signature#
ts
interface CompilerPlugin {
/** Unique name; it appears in every diagnostic and error the plugin causes. */
readonly name: string;
/**
* `"pre"` runs on the tree of the source, before every compiler pass; `"post"` runs on the tree
* of the generated code.
* @default "pre"
*/
readonly enforce?: PluginStage;
/** Every import the plugin may add. Absent means none. */
readonly imports?: readonly PluginImport[];
/**
* Reads the tree and records edits and reports on `context`. Synchronous, and returns nothing.
* @param ast The tree of the module as of this stage.
* @param context Facts, reporting, the walk and the edits.
*/
transform(ast: ProgramNode, context: PluginContext): void;
}
Members#
| Name | Type | Description |
|---|---|---|
name |
readonly name: string |
Unique name; it appears in every diagnostic and error the plugin causes. |
enforce? |
readonly enforce?: PluginStage |
"pre" runs on the tree of the source, before every compiler pass; "post" runs on the tree of the generated code. |
imports? |
readonly imports?: readonly PluginImport[] |
Every import the plugin may add. Absent means none. |
transform |
transform(ast: ProgramNode, context: PluginContext): void |
Reads the tree and records edits and reports on context. Synchronous, and returns nothing. |
Examples#
ts
import { compile, type CompilerPlugin } from "@shadow-js/compiler";
const dropTestIds: CompilerPlugin = {
name: "drop-test-ids",
transform(ast, context) {
context.walk({
JSXAttribute(node) {
if (node.name.type === "JSXIdentifier" && node.name.name === "data-testid") {
context.remove({ start: node.start - 1, end: node.end });
}
},
});
},
};
const result = compile(`export const A = () => <b data-testid="x">hi</b>;`, {
plugins: [dropTestIds],
});
console.log(result.code.includes("data-testid")); // false