简体   繁体   English

使用本地声明文件在TypeScript中导入webpack外部包

[英]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. 在Web应用程序的环境中,已经存在一个模块加载器,并且存在模块“ my-lib”,该模块使用JavaScript编写,并且不附带声明文件。

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). 因此,我想要这个lib,但是要在本地进行模块声明(因为我是当前在此上下文中使用TypeScript的唯一人)。

I tried to set the search path for the declaration file using typeRoots in tsconfig.json . 我试图使用typeRoots中的tsconfig.json设置声明文件的搜索路径。 This worked for /// <reference types="my-lib" /> , but didn't for import "my-lib"; 这适用于/// <reference types="my-lib" /> ,但不适用于import "my-lib"; . Only if I put the @types folder inside the node_modules folder the module resolution would find and import it. 仅当我将@types文件夹放入node_modules文件夹中时,模块解析才能找到并导入它。

Is there any way to set it up, such that I don't need to put @types inside the node_modules folder? 有什么方法可以设置它,这样我就不需要将@types放在node_modules文件夹中了吗?

tsconfig.json: tsconfig.json:

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

@types/my-lib/index.d.ts: @类型/我-LIB / index.d.ts:

interface MyLib {
    ...
}

declare const myLib: MyLib;
export = myLib;

src/entry.ts: SRC / entry.ts:

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

webpack.config.js: webpack.config.js:

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

I made it with the following tsconfig.json (just came to my mind): 我使用以下tsconfig.json (我想到):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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