Search code examples
typescriptimportdslfile-formattranspiler

Adding my own transpiled file format to Typescript imports


I just want to import a file format .xyz whose types are not fixed over all instances of the format:

import { Comment, Article, User } from "./Blog.xyz"

But what I get is the following:

TS2307: Cannot find module './Blog.xyz' or its corresponding type declarations.

What I did so far is the following:

  • I developed a compiler that translates my file format to Typescript.
  • I added a Typescript plugin to get IDE support for my files. Now I am able to autocomplete my types and constants. This was done by adding a ScriptSnapshot when importing my files relatively.
  • I assumed that I need a webpack loader to fill the gap during the Typescript transpilation to Javascript. But it seems I was wrong.
  • Then, I discovered this link here (How to import custom file types in Typescript). It describes how to add a declaration file to the type roots of the tsconfig.json . But that is not an option for me since my files have custom types, they are unique for each instance.
  • I also discovered that you could add own file extensions to require.extensions, but that also did not helped. What am I missing to make the Typescript build or the webpack build working? What is the missing link to avoid the error message above?

Solution

  • There were several mistakes in my approach. For the missing types of Blog.xyz it is sufficient to add a .d.ts file that serves the file extension. Then the error disappears, but the values for this file keep missing.

    For the values my approach was to add a custom webpack loader. Here several issues were blocking me:

    1. the transpiled code needs to be free of errors… I missed a comma within a list.
    2. the import needs to be on a value, not on a type to trigger the inclusion of the transpiled file (but I can also be wrong).
    3. the next loader was ts-loader, whose options need to include the transpileOnly flag.

    A lot of stations were better error messages would help a lot.

    If you are debugging you custom loader, I recommend the inspect-loader and the --stats option of webpack.