1.1.0 • Published 2 years ago

esbuild-plugin-ajv v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

npm

esbuild-plugin-ajv

Installation

With npm:

npm i -D esbuild-plugin-ajv ajv

Or yarn:

yarn add -D esbuild-plugin-ajv ajv

Use-cases

The motivation to pre-compile schemas1:

  • avoids dynamic code evaluation with Function constructor (used for schema compilation) - useful in browser environments where 'unsafe-eval' is not allowed by CSP (Content Security Policy)
  • faster startup times
  • lower memory footprint/bundle size
  • compatible with strict content security policies
  • almost no risk to compile schema more than once
  • better for short-lived environments

Usage

Build config

import esbuild from "esbuild";
import AjvPlugin from "esbuild-plugin-ajv";

esbuild.build({
  /* ... */
  plugins: [
    AjvPlugin({
      extraKeywords: [
        /* Ajv.CodeKeywordDefinition */
      ],
      ajvOptions: {
        coerceTypes: true,
      },
    }),
  ],
  /* ... */
});

Precompile imported schema

import validator from "./someJsonSchema.json?ajv";

/**
 * @description use compiled schema in your code
 */
const validate = (x) => {
  if (!validator(x)) throw validator.errors;
  return x;
};

References