diff --git a/src/routes/advanced-concepts/data.json b/src/routes/advanced-concepts/data.json index 76046c2946..97b42cb6e0 100644 --- a/src/routes/advanced-concepts/data.json +++ b/src/routes/advanced-concepts/data.json @@ -1,4 +1,4 @@ { "title": "Advanced concepts", - "pages": ["fine-grained-reactivity.mdx"] + "pages": ["fine-grained-reactivity.mdx", "jsx-transpilation.mdx"] } diff --git a/src/routes/advanced-concepts/jsx-transpilation.mdx b/src/routes/advanced-concepts/jsx-transpilation.mdx new file mode 100644 index 0000000000..9bd5af5a44 --- /dev/null +++ b/src/routes/advanced-concepts/jsx-transpilation.mdx @@ -0,0 +1,240 @@ +--- +title: JSX transpilation +--- + +Most frameworks using JSX are using so-called "pragma" calls, i.e. `
` are compiled into `h('div')` by the build system. The default template for Solid uses [`vite-plugin-solid`](https://github.com/solidjs/vite-plugin-solid), which itself uses [`babel-preset-solid`](https://github.com/solidjs/solid/tree/main/packages/babel-preset-solid), which uses [`dom-expressions`](https://github.com/ryansolid/dom-expressions) to a very different effect. + +## Setup + +Usually, you would use Solid inside a project that either uses `vite` directly or indirectly through `vinxi`. If you use `rollup` instead, our `vite-plugin-solid` should be compatible with this one, too. Otherwise, if you are using `babel` directly or indirectly, configure it to use `babel-preset-solid`. + + +
+```ts +import { defineConfig } from 'vite'; +import solidPlugin from 'vite-plugin-solid'; + +defineConfig({ plugins: [solidPlugin()] }); +``` +
+
+```ts +import solidPlugin from 'vite-plugin-solid'; + +export default { + input: 'main.js', + output: { dir: 'dist' }, + plugins: [solidPlugin()] +}; +``` +
+
+```json +{ + "presets": [ + "@babel/preset-env", + "babel-preset-solid", + "@babel/preset-typescript" + ] +} +``` +
+
+ +### TypeScript setup + +If you do not use TypeScript, you can skip this part. Since TypeScript expects JSX to conform to the format used by most other frameworks, you need it to preserve the JSX and recognize the types exported by Solid for the JSX: + +```json title="tsconfig.json (Excerpt)" +{ + "compilerOptions": { + "jsxImportSource": "solid-js", + "jsx": "preserve" + } +} +``` + +## Result + +Solid divides JSX into static templates that can be cloned into the DOM and reactive code to fill in the missing parts: + +```tsx {"1":8,10-11,13,19,22,27-28,31,36} {"2":9,20,29,33,37} {"3":12,21,30,38} +import { createSignal } from "solid-js"; +import { render } from "solid-js/web"; + +const [count, setCount] = createSignal(0); + +render( + () => ( + , + document.getElementById("app")!, +); + +// becomes + +import { template as _$template } from "solid-js/web"; +import { delegateEvents as _$delegateEvents } from "solid-js/web"; +import { insert as _$insert } from "solid-js/web"; +var _tmpl$ = /*#__PURE__*/_$template(`