|
| 1 | +# Plugin |
| 2 | + |
| 3 | +`vue-styled-components` supports custom plugins. It allows you to hook into the CSS generation process, enabling customization and extending functionality. By providing `beforeBuild` and `afterBuild` hooks, you can modify elements before they are compiled into CSS and adjust the compiled CSS afterward. This system is flexible and supports both single and multiple callbacks. |
| 4 | + |
| 5 | +## `register` |
| 6 | + |
| 7 | +`register` accepts a plugin object with `beforeBuild` and `afterBuild` hooks. |
| 8 | + |
| 9 | +```ts |
| 10 | +const plugin = register({ |
| 11 | + beforeBuild: (element: Element, index: number, children: Element[]) => {}, |
| 12 | + afterBuild: (css: string) => string | void |
| 13 | +}) |
| 14 | +``` |
| 15 | + |
| 16 | +::: warning NOTES |
| 17 | +The `register` method must be called before `app.mount()`. Otherwise, the plugin will not be registered and the hooks will not be called. |
| 18 | +::: |
| 19 | + |
| 20 | +## `beforeBuild` Hook |
| 21 | + |
| 22 | +The beforeBuild hook is called before any CSS is compiled. It provides access to the element, index, and children involved in the CSS generation process. |
| 23 | + |
| 24 | +### Signature |
| 25 | + |
| 26 | +```ts |
| 27 | +type beforeBuildCallback = (element: Element, index: number, children: Element[]) => void; |
| 28 | +``` |
| 29 | + |
| 30 | +### Parameters: |
| 31 | + |
| 32 | +- **element:** The current element that is being processed. |
| 33 | +- **index:** The index of the current element in the CSS generation sequence. |
| 34 | +- **children:** The children elements associated with the current element. |
| 35 | + |
| 36 | +### Example |
| 37 | + |
| 38 | +::: warning |
| 39 | +If you want to change the output of the CSS, you should change propert of `element.return`. Otherwise, the CSS will not be generated as you expect. |
| 40 | +::: |
| 41 | + |
| 42 | +```ts |
| 43 | +plugin.register({ |
| 44 | + beforeBuild: (element: Element, index: number, children: Element[]) => { |
| 45 | + // Change the element's CSS if it contains a specific value |
| 46 | + if (element.children === 'red') { |
| 47 | + element.return = 'color: blue'; |
| 48 | + } |
| 49 | + } |
| 50 | +}); |
| 51 | +``` |
| 52 | + |
| 53 | +## `afterBuild` Hook |
| 54 | + |
| 55 | +The afterBuild hook is called after CSS has been compiled. It provides access to the CSS. |
| 56 | + |
| 57 | +### Signature |
| 58 | + |
| 59 | +```ts |
| 60 | +type afterBuildCallback = (css: string) => string | void; |
| 61 | +``` |
| 62 | + |
| 63 | +### Parameters: |
| 64 | + |
| 65 | +- **css:** The CSS that has been generated. |
| 66 | + |
| 67 | +### Example |
| 68 | + |
| 69 | +```ts |
| 70 | +plugin.register({ |
| 71 | + afterBuild: (css: string) => { |
| 72 | + // Modify the compiled CSS before returning |
| 73 | + return css.replace(/color:red/g, 'color:blue'); |
| 74 | + } |
| 75 | +}); |
| 76 | + |
| 77 | +``` |
0 commit comments