molefrog / wouter

🥢 A minimalist-friendly ~2.1KB routing for React and Preact

Home Page:https://npm.im/wouter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Get down to 1KB. Reimplement a subset of path-to-regexp

molefrog opened this issue · comments

Right now the gzipped library size is 2KB, 70% of which is path-to-regexp dependency. While path-to-regexp provides a well-known way for developer to describe routes, it seems like we could shrink it's functionality to cover the 99% of use cases.

It would be cool to reimplement a limited subset of the library, so that:

  1. We drop that dependency and make it a zero-dependency library 😎
  2. We reduce the size to be less than 1KB (current bundle size without a matcher is 686B).

For users who still want to use the path-to-regexp functionality and get an advanced syntax we could provide an optional entry point:

import { Router } from "wouter";
import makeMatcher from "wouter/matcher"; 
import pathToRegexp from "path-to-regexp";

<Router matchFn={makeMatcher(pathToRegexp)}>
  ...
</Router>

So ideally it would be nice to define a subset of features we would like to support. Here are my ideas:

  • Always case-insensitive
  • Ignores a slash at the end
  • Matches an entire path
  • Supports named segments /:foo/:bar
  • Supports modifiers: :foo?, :foo* and :foo+
  • No support for unnamed params. All params should have a name.
  • No segment constraints e.g. /:foo(\d+)/

Here is what the library generates:
/^output(?:/)?$/i — matches optional slash at the end & case insensitive. Also for segments:

(default)        :foo   - [1]        ([^\/]+?)
(optional)       :foo?  - [0 - 1]    ([^\/]+?)?
(one or more)    :foo+  - [1 - ∞]    ((?:[^\/]+?)(?:\/(?:[^\/]+?))*)
(zero or more)   :foo*  - [0 - ∞]    ((?:[^\/]+?)(?:\/(?:[^\/]+?))*)?

Ignores a slash at the end

Did this feature end up in wouter? Because my root route doesn't work with path="/", has to be path="".

@gitcatrat It did! path="/" is the right way to do that, see https://codesandbox.io/s/wouter-demo-preact-0lr3n

Can you provide a code sample?