メインコンテンツへスキップ

All Posts

News bits

Valibot, a < 1kb Zod Alternative

去年くらいからバリデータライブラリとして zod が話題です。

Zod は、以下のような特徴を持っています。

  1. 以前から有名な joy や yup と似たようなメソッドチェーンスタイルの API
  2. joi や yup よりも優れた型推論
  3. 良いかはともかく便利なメソッドを積極的に取り入れているため、非常に便利
    1. refine、superRefine なども活用すれば最強に思える
jsx
import { z } from "zod";

const schema = z.object({
  name: z.string().min(2).max(20),
  age: z.number().min(18).max(120),
});

Zod は非常に便利と言われる一方で、メソッドチェーンスタイルであるため、Tree Shaking が難しく、ビルドサイズが大きくなってしまうという点が度々指摘されていました。

2023 年 7 月に登場した Valibot は、API をメソッドチェーンではなく個々の関数として提供することで、Tree Shaking を有効にし、ビルドサイズを Zod に比べて大幅に抑制することが出来るようになっています。

https://www.builder.io/blog/introducing-valibot

jsx
import {
  object,
  string,
  number,
  minLength,
  maxLength,
  minValue,
  maxValue,
} from "valibot";

const schema = object({
  name: string([minLength(2), maxLength(20)]),
  age: number([minValue(18), maxValue(120)]),
});

現時点では、Zod から Valibot に乗り換えている人はそこまでいないように思われますが、Zod とよく合わせて使われるreact-hook-form の resolver が提供されるようになれば、今後使用率が増えるのではないかなと思っています。

https://github.com/react-hook-form/resolvers/pull/602

著者について

Hi there. I'm hrdtbs, a frontend expert and technical consultant. I started my career in the creative industry over 13 years ago, learning on the job as a 3DCG modeler and game engineer in the indie scene.

In 2015 I began working as a freelance web designer and engineer. I handled everything from design and development to operation and advertising, delivering comprehensive solutions for various clients.

In 2016 I joined Wemotion as CTO, where I built the engineering team from the ground up and led the development of core web and mobile applications for three years.

In 2019 I joined matsuri technologies as a Frontend Expert, and in 2020 I also began serving as a technical manager supporting streamers and content creators.

I'm so grateful to be working in this field, doing something that brings me so much joy. Thanks for stopping by.