How to dynamically load json schema in typescript using webpack

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. , . :

/**
 * 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;
}

, , 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.

?

+4
1

appendTsSuffixTo

, , ts-loader appendTsSuffixTo, , . , / Person.

appendTsSuffixTo, this.resourcePath = this.resourcePath + '.ts'; ( ) . - :

  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
            appendTsSuffixTo: [/\.schema.json$/]
          }
      },
      {
        test: /\.schema\.json$/,
        loader: 'ts-loader!my-own-loader',
        exclude: /(node_modules)/,
      },
    ]
  },

typings.d.ts, .

?

, ; , appendTsSuffixTo. ts-loader, , .

resourcePath, ts-loader/dist/index.js , ts-loader/dist/servicesHost.js .

, resolveModuleName() return undefined example.schema.json, this.resourcePath . , , appendTsSuffixTo.

( ) ts-loader, , this.resourcePath .schema.json , .

- - ; IDE - . . , this Github repo , .

+2

Source: https://habr.com/ru/post/1690898/


All Articles