'How do I reference json schema emitted by wepack?
I work on a Electron project that uses Webpack. I use json schemas, configured like this:
module.exports = {
module: {
rules: [
{
test: /\.schema.json$/,
type: "asset/resource",
generator: {
filename: "schemas/[name].json",
},
}
]
}
}
So, if I have somewhere in my sources file some-config.schema.json that looks like this:
{
"$id": "/schemas/some-config",
"$ref": "/schemas/other-config"
}
It is emitted as http://localhost:1212/dist/schemas/some-config.schema.json. Notice 1212 — this is port number that is configured dynamically by different tools that configure the build, so I can't even know that path when I write code or schemas.
However, the $ref above doesn't work:
Problems loading reference 'file:///schemas/other-config': Unable to load schema from '/schemas/other-config': Failed to fetch.
I would want for it to load http://localhost:1212/dist/schemas/other-config.schema.json. How do I set up this reference?
Solution 1:[1]
The value of $ref is a URI, and not a URL. This matters because the URI is not necessarily "network addressable", aka, not a real network address.
The value of $id is an identifier only.
When a JSON Schema parser gets a value in $id which is a relative URI, if it can't determine a base URI to resolve to an absolute URI, then it should make one up. So, pretend it makes one up, or uses https://example.com.
So, when you use an $id value of /schemas/other-config, we can pretend it's prefixed with https://example.com, and so resolves to https://example.com/schemas/other-config. The same is true for /schemas/some-config.
When a JSON Schema processes the schema you've provided, it should first be using the URI resolution process, matching up references with it's index of $id values to schemas.
Essentially, set up correctly, your schema files could be located anywhere, as long as they have the correct $id values, and you've loaded them in to the implementation you're using.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Relequestual |
