Import webpack externals package in TypeScript with local declaration file

4.6k views Asked by At

I'm trying to import an external module in my typescript module. In the environment of the web app there already is a module loader and the module "my-lib" is present, which is written in JavaScript and does not ship with a declaration file.

So, I want to require this lib, but have the module declaration locally (as I am the only one currently using TypeScript in this context).

I tried to set the search path for the declaration file using typeRoots in tsconfig.json. This worked for /// <reference types="my-lib" />, but didn't for import "my-lib";. Only if I put the @types folder inside the node_modules folder the module resolution would find and import it.

Is there any way to set it up, such that I don't need to put @types inside the node_modules folder?

tsconfig.json:

{
    "compilerOptions": {
        "esModuleInterop": true,
        "typeRoots": [
            "./@types"
        ]
    },
    "include": [
        "src/**/*"
    ]
}

@types/my-lib/index.d.ts:

interface MyLib {
    ...
}

declare const myLib: MyLib;
export = myLib;

src/entry.ts:

import myLib from "my-lib";
...

webpack.config.js:

...
externals: {
    "my-lib": "my-lib"
},
...
1

There are 1 answers

0
Florian Bachmann On

I made it with the following tsconfig.json (just came to my mind):

{
    "compilerOptions": {
        "esModuleInterop": true,
        "typeRoots": [
            "./@types"
        ],
        "baseUrl": ".",
        "paths": {
            "*": [
                "*",
                "@types/*"
            ]
        }
    },
    "include": [
        "src/**/*",
        "@types/**/*"
    ]
}