1.0.5 • Published 10 months ago

@orderlycode/vite-file-router v1.0.5

Weekly downloads
-
License
ISC
Repository
-
Last release
10 months ago

vite-tools

vite용 파일 라우터

bun install @orderlycode/vite-tools react-router-dom
mkdir src/routes

폴더를 이용한 Router

Next.js app router와 거의 비슷하게 만들어놨다. routes 폴더를 기준으로 라우팅하려면 아래와 같이 만들면 된다.

import {createBrowserRouter, RouterProvider} from "react-router-dom";
import {createRouteObjects} from "@orderlycode/vite-tools";
import {Suspense} from "react";
import ReactDOM from "react-dom/client";
import React from "react";
import "@orderlycode/vite-tools/index.css"
import "./index.css"

const routes = import.meta.glob(
  "./routes/**/{layout,page,loading,not-found,error}.tsx",
  {import: "default"},
);
const router = createBrowserRouter(createRouteObjects(routes, "./routes"));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <RouterProvider router={router} />
    </Suspense>
  );
}

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
);

관련 함수

// http://localhost:3000/test?a=1 -> /test?a=1
usePathInHost()

// http://localhost:3000/test?a=1 -> /test
usePathname();

// routes 폴더 -> /shop/[tag]/[item] -> tag, item 얻음
usePathParam()

// http://localhost:3000/test?a=1 -> a 값 얻음
useQuery()

// react-router-dom꺼 -> searchParams 읽고 쓰기 가능
useSearchParams()

routes 폴더

npm.io npm.io

폴더 구조

  • (test) -> url에 안들어가는데 그룹핑 가능
  • [id] -> usePathParam('id')로 조회가능
  • 이외 모든 폴더는 그대로 url에 반영됨

예제

src/routes/layout.tsx

import {Layers, LayoutProps} from "@orderlycode/vite-tools";

export default function Component({children}: LayoutProps) {
  return (
    <>
      {children}
      <Layers/>
    </>
  );
}

src/routes/error.tsx

import {ErrorProps} from "@/utils/routes/ErrorProps.ts";

export default function Component({error}: ErrorProps) {
  return (
    <div>
      <div>{import.meta.url}</div>
      <pre>{error.stack}</pre>
    </div>
  );
}

다른 파일들

export default function Component() {
  return (
    <div>{import.meta.url}</div>
  );
}

helpers

  • /test?a=1 -> useQuery('a') === '1', useURLSearchParams().get('a') === '1'
  • /[id] + /123 -> usePathParam('id') === '123'
  • /test + /test -> usePathname() === '/test'

참고자료

1.0.5

10 months ago

1.0.4

10 months ago

1.0.3

10 months ago

1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago