I have a json diagram describing a Person object . I would like to be able to load this schema into a typescript file as follows:
import Person from './schema/person.schema.json';
To do this, I created a loader that converts the json file into a typescript interface declaration (using json-schema-to-typescript ), and then pass the result to the ts loader.
My web package is configured this way:
webpack.config.js (excerpt)
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
},
{
test: /\.schema\.json$/,
loader: 'ts-loader!jsonschema-loader',
exclude: /(node_modules)/,
},
]
},
After this question, I set up the declaration so that the json file is considered a string:
declaration.d.ts
declare module '*.schema.json' {
const schema: string;
export default schema;
}
, , ts-loader , person.schema.ts. , . :
export interface Person {
firstName: string;
lastName: string;
age?: number;
[k: string]: any;
}
, , Person :
index.js
import Person from './schema/person.schema.json';
const person: Person = {
lastName: 'Doe',
firstName: 'John',
};
console.log(person);
:
ERROR in ./src/index.ts
(3,15): error TS2304: Cannot find name 'Person'.
.schema.json , (this.resourcePath) ts , ts-loader ts Person.
?