📚ReDocs
ReDocs

Import from:

1import { Plugin } from "@reface/recast";

Plugin Context

Plugins receive a rich context for working with templates:

1class MyPlugin {
2 ​name = "my-plugin";
3
4 ​processNode(context: RenderContext) {
5 ​ ​const {
6 ​ ​ ​// Core
7 ​ ​ ​template, // Current template
8 ​ ​ ​html, // Current HTML (if exists)
9
10 ​ ​ ​// Query API
11 ​ ​ ​query: {
12 ​ ​ ​ ​is, // Check node type
13 ​ ​ ​ ​matches, // Check selector
14 ​ ​ ​ ​closest, // Find nearest ancestor
15 ​ ​ ​ ​find, // Find descendants
16 ​ ​ ​ ​parent, // Parent node
17 ​ ​ ​},
18
19 ​ ​ ​// Helpers
20 ​ ​ ​utils: {
21 ​ ​ ​ ​isTemplate, // Check if Template
22 ​ ​ ​ ​isComponent, // Check if Component
23 ​ ​ ​ ​isElement, // Check if Element
24 ​ ​ ​ ​isEmpty, // Check if empty value
25 ​ ​ ​},
26
27 ​ ​ ​// Storage
28 ​ ​ ​store: {
29 ​ ​ ​ ​get, // Get plugin data
30 ​ ​ ​ ​set, // Store plugin data
31 ​ ​ ​},
32 ​ ​} = context;
33
34 ​ ​// Usage examples
35 ​ ​if (query.is(template, "button")) {
36 ​ ​ ​// Process buttons
37 ​ ​}
38
39 ​ ​if (query.matches(template, "[data-action]")) {
40 ​ ​ ​// Process elements with data-action
41 ​ ​}
42
43 ​ ​const form = query.closest(template, "form");
44 ​ ​const inputs = query.find(template, "input");
45
46 ​ ​// Store data
47 ​ ​store.set("my-plugin", { count: inputs.length });
48 ​}
49}

Plugin Lifecycle

Plugins can hook into different render phases:

1class MyPlugin {
2 ​// Initialization
3 ​setup(recast) {
4 ​ ​// Access to Recast instance
5 ​}
6
7 ​// Before render
8 ​beforeRender(context) {
9 ​ ​// Setup
10 ​}
11
12 ​// During render
13 ​processNode(context) {
14 ​ ​// Node transformation
15 ​ ​return node;
16 ​}
17
18 ​// After render
19 ​afterRender(context) {
20 ​ ​// Final processing
21 ​}
22}

Built-in Plugins

LoggerPlugin

Debug render process:

1const logger = new LoggerPlugin();
2recast.use(logger);
3
4// After rendering
5console.log(logger.toText());
6// Outputs detailed render process log

StyledPlugin

Process CSS-in-JS styles:

1recast.use(new StyledPlugin());
2
3// Now styled components will work
4const Button = styled.button/*css*/ `
5 ​& {
6 ​ ​color: red;
7 ​}
8`;

Plugin Communication

Plugins can exchange data through store:

1// Plugin A
2store.set("shared-data", { value: 123 });
3
4// Plugin B
5const data = store.get("shared-data");

Best Practices

  1. Unique Names

    • Use unique plugin names

    • Prefixes for related plugins

  2. Data Isolation

    • Store data in plugin store

    • Use unique keys

  3. Performance

    • Minimize operations in processNode

    • Cache results where possible

  4. Type Safety

    • Define types for store data

    • Use types for context