(_options = {})
| 186 | |
| 187 | export const componentToAlpine: TranspilerGenerator<ToAlpineOptions> = |
| 188 | (_options = {}) => |
| 189 | ({ component }) => { |
| 190 | const options = initializeOptions({ target: 'alpine', component, defaults: _options }); |
| 191 | |
| 192 | let json = fastClone(component); |
| 193 | if (options.plugins) { |
| 194 | json = runPreJsonPlugins({ json, plugins: options.plugins }); |
| 195 | } |
| 196 | const css = collectCss(json); |
| 197 | stripMetaProperties(json); |
| 198 | if (options.plugins) { |
| 199 | json = runPostJsonPlugins({ json, plugins: options.plugins }); |
| 200 | } |
| 201 | |
| 202 | const componentName = camelCase(json.name) || 'MyComponent'; |
| 203 | |
| 204 | const stateObjectString = getStateObjectString(json); |
| 205 | // Set x-data on root element |
| 206 | json.children[0].properties['x-data'] = options.inlineState |
| 207 | ? stateObjectString |
| 208 | : `${componentName}()`; |
| 209 | |
| 210 | if (hasRootUpdateHook(json)) { |
| 211 | json.children[0].properties['x-effect'] = 'onUpdate'; |
| 212 | } |
| 213 | |
| 214 | let str = css.trim().length ? `<style>${css}</style>` : ''; |
| 215 | str += json.children.map((item) => blockToAlpine(item, options)).join('\n'); |
| 216 | |
| 217 | if (!options.inlineState) { |
| 218 | str += `<script> |
| 219 | ${babelTransformCode(`document.addEventListener('alpine:init', () => { |
| 220 | Alpine.data('${componentName}', () => (${stateObjectString})) |
| 221 | })`)} |
| 222 | </script>`; |
| 223 | } |
| 224 | |
| 225 | if (options.plugins) { |
| 226 | str = runPreCodePlugins({ json, code: str, plugins: options.plugins }); |
| 227 | } |
| 228 | if (options.prettier !== false) { |
| 229 | try { |
| 230 | str = format(str, { |
| 231 | parser: 'html', |
| 232 | htmlWhitespaceSensitivity: 'ignore', |
| 233 | plugins: [ |
| 234 | // To support running in browsers |
| 235 | require('prettier/parser-html'), |
| 236 | require('prettier/parser-postcss'), |
| 237 | require('prettier/parser-babel'), |
| 238 | ], |
| 239 | }); |
| 240 | } catch (err) { |
| 241 | console.warn('Could not prettify', { string: str }, err); |
| 242 | } |
| 243 | } |
| 244 | if (options.plugins) { |
| 245 | str = runPostCodePlugins({ json, code: str, plugins: options.plugins }); |
no test coverage detected