I have a json schema describing an object Person. I would like to be able to load that schema into a typescript file directly this way:
import Person from './schema/person.schema.json';
For this, I created a loader which convert the json file to a typescript interface declaration (using json-schema-to-typescript) and then pass the result to ts-loader.
My webpack 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)/,
},
]
},
Following this question I configured a declaration so that the json file is considered a string:
declaration.d.ts:
declare module '*.schema.json' {
const schema: string;
export default schema;
}
My loader changes the filename it processes on the fly, so what the ts-loader think it loads is person.schema.ts
. Moreover, I have checked the result of my loader is correct. Here it is:
/**
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
export interface Person {
firstName: string;
lastName: string;
/**
* Age in years
*/
age?: number;
[k: string]: any;
}
However, when I build my project, Person is not recognized as an object and the compilation fails:
index.js
import Person from './schema/person.schema.json';
const person: Person = {
lastName: 'Doe',
firstName: 'John',
};
console.log(person);
compilation fails with:
ERROR in ./src/index.ts
(3,15): error TS2304: Cannot find name 'Person'.
Although I defines the export of .schema.json file as string in my declaration, my loader dynamically changes the filename (this.resourcePath) to a ts file so the ts-loader should see it as a standard ts file and export the Person object.
What am I doing wrong?