DEV Community

Brama Udi
Brama Udi

Posted on • Updated on

Add vite-plugin-pages to SolidJS

Since official SolidJS starter template are vite-based we can easily use vite-plugin-pages to create automatic routing a.k.a file based routing with official solid-app-router package.

First create a new project by running these commands in your terminal:

> npx degit solidjs/templates/js my-app
> cd my-app
> npm i # or yarn or pnpm
> npm run dev # or yarn or pnpm
Enter fullscreen mode Exit fullscreen mode

Or for TypeScript:

> npx degit solidjs/templates/ts my-app
> cd my-app
> npm i # or yarn or pnpm
> npm run dev # or yarn or pnpm
Enter fullscreen mode Exit fullscreen mode

Then install the router dependencies:

> npm i solid-app-router
> npm i -D vite-plugin-pages@v0.18.2 
Enter fullscreen mode Exit fullscreen mode

Configure vite.config.js:

import { defineConfig } from 'vite';
import solidPlugin from 'vite-plugin-solid';
+ import Pages from 'vite-plugin-pages';

export default defineConfig({
  plugins: [
+    Pages({
+      react: true,
+      importMode: 'async',
+    }),
    solidPlugin()
  ],
  build: {
    target: 'esnext',
    polyfillDynamicImport: false,
  },
});
Enter fullscreen mode Exit fullscreen mode

Then src/index.jsx:

import { render } from "solid-js/web";
import { Router } from "solid-app-router";
import App from "./App";

render(
  () => (
    <Router>
      <App />
    </Router>
  ),
  document.getElementById("root")
);
Enter fullscreen mode Exit fullscreen mode

And finally src/App.jsx:

import { useRoutes, Link } from "solid-app-router";
import { lazy } from "solid-js";
import routes from 'virtual:generated-pages'

export default function() {
  const Routes = useRoutes(routes.map(route => ({
    ...route,
    component: lazy(route.component)
  })));
  return (
    <>
      <h1>Solid App</h1>
      <ul>
        <li><Link href="/">Home</Link></li>
        <li><Link href="/about">About</Link></li>
      </ul>
      <Routes />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note: use vite-plugin-pages v0.18.2, the greater version contains breaking changes and the Solid implementation seems more complicated. :/

Top comments (0)