Compile and pack JSON schema definitions on import using esbuild
The package is released to npm as @offen/esbuild-plugin-jsonschema
:
npm install @offen/esbuild-plugin-jsonschema -D
In the default configuration, the transform is applied to all files with a .schema
or .schema.json
extension. The transformed module will export the packed AJV validate
function.
In your application:
const validateFoo = require('./foo.schema')
const ok = validateFoo({ foo: true })
if (!ok) {
console.log(validateFoo.errors)
throw new Error('Foo did not validate')
}
When bundling:
const esbuild = require('esbuild')
const jsonschemaPlugin = require('@offen/esbuild-plugin-jsonschema')
esbuild.build({
entryPoints: ['app.js'],
bundle: true,
plugins: [jsonschemaPlugin()],
outdir: './public'
})
Schemas are expected to be defined in JSON format and saved as .schema
files:
{
"type": "string",
"maxLength": 128
}
The transform accepts the following options as its 2nd arguments:
By default, this plugin only compiles "secure" schemas. This can be disabled by passing secure: false
to the transform.
By default, files with a .schema
or a .schema.json
extension are compiled. If you have different requirements you can pass a Regexp to filter
for the plugin to use.
Includes ajv-formats. Default true
.
Custom options to be passed to Ajv constructor.
New versions can be released using npm version <patch|minor|major>
. Make sure you are authenticated against the @offen
scope with npm.
Copyright 2021 Frederik Ring - Available under the MIT License