title: How to dynamically load json schema to typescript with webpack
body: <p>I have a json schema describing an object <a href="http://json-schema.org/examples.html" rel="noreferrer">Person</a>. I would like to be able to load that schema into a typescript file directly this way:</p>
  
  <pre><code>import Person from './schema/person.schema.json';
  </code></pre>
  
  <p>For this, I created a loader which convert the json file to a typescript interface declaration (using <a href="https://www.npmjs.com/package/json-schema-to-typescript" rel="noreferrer">json-schema-to-typescript</a>) and then pass the result to ts-loader.</p>
  
  <p>My webpack is configured this way:</p>
  
  <p><strong>webpack.config.js</strong> (excerpt)</p>
  
  <pre><code>module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
      },
      {
        test: /\.schema\.json$/,
        loader: 'ts-loader!jsonschema-loader',
        exclude: /(node_modules)/,
      },
    ]
  },
  </code></pre>
  
  <p>Following this <a href="https://stackoverflow.com/questions/46503615/import-html-from-typescript-with-webpack">question</a> I configured a declaration so that the json file is considered a string:</p>
  
  <p><strong>declaration.d.ts</strong>:</p>
  
  <pre><code>declare module '*.schema.json' {
    const schema: string;
    export default schema;
  }
  </code></pre>
  
  <p>My loader changes the filename it processes on the fly, so what the ts-loader think it loads is <code>person.schema.ts</code>. Moreover, I have checked the result of my loader is correct. Here it is:</p>
  
  <pre><code>/**
   * 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;
  }
  </code></pre>
  
  <p>However, when I build my project, Person is not recognized as an object and the compilation fails:</p>
  
  <p><strong>index.js</strong></p>
  
  <pre><code>import Person from './schema/person.schema.json';
  
  const person: Person = {
    lastName: 'Doe',
    firstName: 'John',
  };
  console.log(person);
  </code></pre>
  
  <p>compilation fails with:</p>
  
  <pre><code>ERROR in ./src/index.ts
  (3,15): error TS2304: Cannot find name 'Person'.
  </code></pre>
  
  <p>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.</p>
  
  <p>What am I doing wrong?</p>