简体   繁体   中英

Import webpack externals package in TypeScript with local declaration file

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM