Skip to content

Commit

Permalink
✨ auto. hmr
Browse files Browse the repository at this point in the history
  • Loading branch information
amoutonbrady committed Jul 31, 2020
1 parent bfa4da5 commit d96fcf2
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 18 deletions.
15 changes: 2 additions & 13 deletions playground/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,5 @@ import { render } from "solid-js/dom";

const App = () => <h1>Hello world!!!</h1>;

const rootEl = document.getElementById("app");
const dispose = render(() => App, rootEl);

// HMR stuff, this will be automatically removed during build
// /!\ You need to add "vite" in the "compilerOptions.types" of your tsconfig.json
// if you want to avoid type errors here
if (import.meta.hot) {
import.meta.hot.accept();
import.meta.hot.dispose(() => {
dispose();
rootEl.textContent = "";
});
}
export const rootEl = document.getElementById("app");
export const dispose = render(() => App, rootEl);
4 changes: 0 additions & 4 deletions playground/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ const config: UserConfig = {
root: "src",
outDir: "dist",
plugins: [solidPlugin()],
// Vite and Esbuild being opinionated about how to manage JSX,
// you need to disable it to prevent extra stuff going in your bundle
// Luckily, vite is still quite fast even skipping Esbuild
enableEsbuild: false,
};

export default config;
21 changes: 20 additions & 1 deletion src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
RollupBabelInputPluginOptions,
} from "@rollup/plugin-babel";
import { transformFileAsync, TransformOptions } from "@babel/core";
import dd from "dedent";

export function solidPlugin(options?: SolidPluginOptions): Plugin {
const babel = options?.babel ?? {};
Expand Down Expand Up @@ -52,7 +53,7 @@ export function solidPlugin(options?: SolidPluginOptions): Plugin {
// If the transformation is successful, return it as as js content
if (result) {
ctx.type = "js";
ctx.body = result.code;
ctx.body = addHMR(result.code);
ctx.map = result.map;
return;
}
Expand All @@ -62,9 +63,27 @@ export function solidPlugin(options?: SolidPluginOptions): Plugin {
await next();
});
},
enableRollupPluginVue: false,
};
}

function addHMR(code: string) {
if (!code.includes(`const dispose`)) return code;
if (!code.includes(`const rootEl`)) return code;

return dd`
${code}
if (import.meta.hot) {
import.meta.hot.accept();
import.meta.hot.dispose(() => {
dispose();
rootEl.textContent = "";
});
}
`;
}

export default solidPlugin;

// TYPES
Expand Down

0 comments on commit d96fcf2

Please sign in to comment.