With npm:
npm i -D esbuild-plugin-ajv ajv
Or yarn:
yarn add -D esbuild-plugin-ajv ajv
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
import esbuild from "esbuild";
import AjvPlugin from "esbuild-plugin-ajv";
esbuild.build({
/* ... */
plugins: [
AjvPlugin({
extraKeywords: [
/* Ajv.CodeKeywordDefinition */
],
ajvOptions: {
coerceTypes: true,
},
}),
],
/* ... */
});
import validator from "./someJsonSchema.json?ajv";
/**
* @description use compiled schema in your code
*/
const validate = (x) => {
if (!validator(x)) throw validator.errors;
return x;
};
- [1]: Standalone Validation Code in Ajv documentation https://ajv.js.org/guide/managing-schemas.html#standalone-validation-code