Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import custom file types in Typescript

As a bit of a fun project, I'm making a "framework" for creating native web components. I've created a webpack loader that parses some XML in custom .comp files and exports an es2015 class. Unfortunately, I can't find a way to import these .comp files in my typescript files.

I've tried importing my custom files in a regular javascript file, and everything works as expected; I can see the loader I created running, and I get the expected output. But when I try to import in a typescript file I just get the error Cannot find module 'test/test.comp'. I tried creating an empty declaration file and noticed the error message changes to File '[path]/test/test.d.ts' is not a module

Here's my webpack config:

mode: 'development',
watch: true,
entry: './test/main.js',
output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build')
},
module: {
    rules: [
        {
            test: /\.ts/,
            use: 'ts-loader',
            exclude: /node_modules/
        },
        {
            test: /\.comp/,
            use: path.resolve(__dirname, 'core/compose-loader.js'),
            exclude: /node_modules/
        }
    ]
},
resolve: {
    extensions: ['.js', '.ts', '.comp'],
    alias: {
        'core': path.resolve(__dirname, "core/"),
        'test': path.resolve(__dirname, "test/")
    }
}

And my tsconfig.json

{
    "compilerOptions": {
        "outDir": "build",
        "baseUrl": ".",
        "paths": {
            "core": ["core/*"],
            "test": ["test/*"]
        },
        "target": "es2015",
        "typeRoots": ["./core"]

    },
    "include": [
        "test/*.ts"
    ],
    "exclude": [
        "core",
        "node_modules",
        "**/*.comp"
    ]
}
like image 920
heavygl0w Avatar asked Sep 28 '19 20:09

heavygl0w


1 Answers

You can define the types for all these files with *.comp in a declarations.d.ts file (or whatever name you choose).

declare module "*.comp" {
  const value: any; // Add better type definitions here if desired.
  export default value;
}

You may need to also add this to typeRoots in your tsconfig.json

{
    "compilerOptions": {
        // Other configuration...
        "typeRoots": [
            "./src/declarations.d.ts"
        ]
    }
}

And now, import value from "./test.comp" should work as expected (at least the types).

Note: for VSCode the definition file should not be higher in the folder structure than the import.

like image 137
skovy Avatar answered Sep 22 '22 15:09

skovy