@fleur/froute

中文文档
1.0.9发布于 2023/10/23MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2179

Type safe and flexible router for React

原始使用文档
文档目录8 节
  1. Features
  2. API Overview
  3. Hooks
  4. Components
  5. Getting started
  6. Next.js compat status
  7. Why froute provides Next.js compat hooks?
  8. How to type-safe useRoute

CI latest BundleSize License npm

Froute

CHANGELOG

Framework independent Router for React.
Can use with both Fleur / Redux (redux-thunk).

With provides Next.js subset useRouter

yarn add @fleur/froute

Features

See all examples in this spec or examples

  • Library independent
    • Works with Redux and Fleur
  • Next.js's Router subset compatiblity (useRouter, withRouter)
  • Supports dynamic import without any code transformer
  • Supports Sever Side Rendering
    • Supports preload
    • ResponseCode and Redirect component
  • Custom route resolution (for i18n support)
  • URL Builder

API Overview

Hooks

  • useRouter - Next.js subset compat hooks
    • withRouter available
  • useFrouteRouter - useRouter superset (not compatible to Next.js's useRouter)
  • useRouteComponent
  • useBeforeRouteChange(listener: () => Promise<boolean | void> | boolean | void)
    • It can prevent routing returns Promise<false> | false
Deprecated APIs

The following hooks are deprecated. These features are available from useFrouteRouter.

  • useParams
  • useLocation
  • useNavigation
  • useUrlBuilder

Components

  • <Link href={string} />
  • <FrouteLink to={routeDef} params={object} query={object} /> - Type-safe routing
  • <ResponseCode status={number} />
  • <Redirect url={string} status={number = 302}

Getting started

Route definition:

export const routes = {
  index: routeOf('/').action({
    component: () => import('./pages/index'),
  }),
  user: routeOf('/users/:userId').action({
    component: () => import('./pages/user'),
    preload: (store: Store, params /* => inferred to { userId: string } */) =>
      Promise.all([ store.dispatch(fetchUser(param.userId)) ]),
  })
}

App:

import { useRouteComponent, ResponseCode } from '@fleur/froute'

export const App = () => {
  const { PageComponent } = useRouteComponent()

  return (
    <div>
      {PageComponent ? (
        <PageComponent /> 
      ) : (
        <ResponseCode status={404}>
          <NotFound />
        </ResponseCode>
      )}
    </div>
  )
}

User.tsx:

import { useRouter, buildPath } from '@fleur/froute'
import { routes, ResponseCode, Redirect } from './routes'

export default () => {
  const { query: { userId } } = useRouter()
  const user = useSelector(getUser(userId))

  if (!user) {
    return (
      <ResponseCode status={404}>
        <NotFound />
      </ResponseCode>
    )
  }

  if (user.suspended) {
    return (
      <Redirect status={301} url='/'>
        This account is suspended.
      </Redirect>
    )
  }
  
  return (
    <div>
      Hello, {user.name}!
      <br />
      <Link href={buildPath(routes.user, { userId: '2' })}>
        Show latest update friend
      </Link>
    </div>
  )
}

Server side:

import { createRouter } from '@fleur/froute'
import { routes } from './routes'

server.get("*", async (req, res, next) => {
  const router = createRouter(routes, {
    preloadContext: store
  })

  await router.navigate(req.url)
  await context.preloadCurrent();

  const content = ReactDOM.renderToString(
    <FrouteContext router={router}>
      <App />
    </FrouteContext>
  )

  // Handling redirect
  if (router.redirectTo) {
    res.redirect(router.statusCode, router.redirectTo)
  } else{
    res.status(router.statusCode)
  }
  
  const stream = ReactDOM.renderToNodeStream(
    <Html>
      {content}
    </Html>
  ).pipe(res)

  router.dispose()
})

Client side:

import { createRouter, FrouteContext } from '@fleur/froute'

domready(async () => {
  const router = createRouter(routes, {
    preloadContext: store,
  });

  await router.navigate(location.href)
  await router.preloadCurrent({ onlyComponentPreload: true })

  ReactDOM.render((
      <FrouteContext router={router}>
        <App />
      </FrouteContext>
    ),
    document.getElementById('root')
  )
})

Next.js compat status

  • Compat API via useRouter or withRouter
    • Compatible features
      • query, push(), replace(), prefetch(), back(), reload()
      • pathname is provided, but Froute's pathname is not adjust to file system route.
    • Any type check not provided from Next.js (Froute is provided, it's compat breaking)
  • Next.js specific functions not supported likes asPath, isFallback, basePath, locale, locales and defaultLocale
    • <Link /> only href props compatible but behaviour in-compatible.
      • Froute's Link has <a /> element. Next.js is not.
      • as, passHref, prefetch, replace, scroll, shallow is not supported currently.
    • pathname is return current location.pathname, not adjust to component file path base pathname.
    • router.push(), router.replace()
      • URL Object is does not support currentry
      • as argument is not supported
    • router.beforePopState is not supported
      • Use useBeforeRouteChange() hooks instead
    • router.events
      • Partially supported: routeChangeStart, routeChangeComplete, routeChangeError
        • Only url or err arguments.
        • Not implemented: err.cancelled and { shallow } flag.
      • Not implemented: beforeHistoryChange, hashChangeStart, hashChangeComplete

Why froute provides Next.js compat hooks?

It aims to migrate to Next.js from react-router or another router.

Froute's useRouter aims to provide a useRouter that is partially compatible with the Next.js useRouter, thereby guaranteeing an intermediate step in the migration of existing React Router-based applications to Next.js.

How to type-safe useRoute

Use this snippet in your app. (It's breaking to Type-level API compatibility from Next.js)

// Copy it in-your-app/useRouter.ts
import { useRouter as useNextCompatRouter } from '@fleur/froute'
export const useRouter: UseRouter = useNextCompatRouter

Usage:

// Route definition
const routes = {
  users: routeOf('/users/:id'),
}

// Typeing to `Routes`, it's free from circular dependency
export type Routes = typeof routes

// Component
import { useRouter } from './useRouter'
import { Routes } from './your-routes'

const Users = () => {
  const router = useRouter<typeof Routes['users']>()
  router.query.id // It infering to `string`.
}

版本与发布记录

@fleur/froute 共发布 81 个版本,首次发布于 2020/12/17;过去 12 个月发布了 0 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.0.9latest2023/10/233 年前
1.0.8dev2023/10/193 年前
1.0.8-dev2023/10/193 年前
1.0.72023/10/133 年前
1.0.62023/10/133 年前
1.0.52023/10/033 年前

其他发布通道:beta → 1.0.0-beta.12,dev → 1.0.8。

关于 @fleur/froute 的常见问题

@fleur/froute 是什么?

Type safe and flexible router for React

如何安装 @fleur/froute?

在项目目录运行 npm install @fleur/froute,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>= 16.8.x)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fleur/froute 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fleur/froute 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@fleur/froute 可以商用吗?

@fleur/froute 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fleur/froute 的下载量有多少?

根据 npm 官方下载统计,@fleur/froute 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,179 次,日均约 73 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fleur/froute 还在维护吗?

最新版本 1.0.9 发布于 2023/10/23(3 年前);至今共发布 81 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/12/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。