A demonstration of how transform a Svelte component to a React component. (derived from https://github.com/joshnuss/micro-svelte-compiler)
Download and install dependencies:
git clone https://github.com/amen-souissi/svelte-to-react-compiler
cd svelte-to-react-compiler
nm install
npm install -g babel-cli
npm link
This compiler has multiple stages:
.svelte
file and extract code from <script>
tags and build a list of non-<script>
tags.export let ...
is a prop)stdout
It uses similar dependencies to svelte.js (except for HTML parsing).
Say you have a .svelte
file like examples/component.svelte
:
<script>
export let count;
export let name;
function reset(e) {
e.preventDefault();
count = 0;
}
</script>
<h1 class="c1" on:click="reset">Hello {name} {count}!</h1>
<div>Svelte to <b>React</b>!</div>
Run the compiler on it:
svelte-to-react examples/component.svelte > examples/component.jsx
It generates a JavaScript file that looks like this:
import * as React from "react";
export default function Component({ count, name }) {
const [countState, setCountState] = React.useState(count);
React.useEffect(() => {
setCountState(count);
}, [count]);
function reset(e) {
e.preventDefault();
setCountState(0);
}
return (
<React.Fragment>
<h1 className="c1" onClick={reset}>
Hello {name} {countState}!
</h1>
<div>
Svelte to <b>React</b>!
</div>
</React.Fragment>
);
}
MIT