【问题标题】:Using Leaflet or any js library with Typescript and webpack使用 Leaflet 或任何带有 Typescript 和 webpack 的 js 库
【发布时间】:2021-03-20 22:19:54
【问题描述】:

注意:我搜索了很多,但找不到答案。

我正在尝试通过扩展leaflet 创建一个地图库。但我认为我的问题是一般使用js 库。我正在使用webpackts-loader 创建输出文件。

我已经安装了 @types/geojson@types/leaflet 类型并将它们移动到 modules 文件夹中。

这是我的简单 Test1.ts 文件:

import * as L from './modules/@types/leaflet/index';
import { MyDataItem } from './MyDataItem ';

export class Test1 {
    text: string;
    data: MyDataItem ;
    latLng: L.LatLng;
   
    constructor(theName: string) {
        this.data = { name: theName} as MyDataItem ;
    }
    public show() {
        console.log(this.data.name);
    }

    public showLatLng() {
        this.latLng = new L.LatLng(22, 55);
        console.log(this.latLng);
    }
}

module.exports = {
    Test1: Test1
}

我在我的 webpack 输出选项中设置了 library:'lib'。 现在我从浏览器控制台调用以下方法:

> (new lib.Test1("aa")).show()        // result: aa
> (new lib.Test1("aa")).showLatLng()   // error : L.LatLng is not a constructor
// or if it set webpack optimization:minimize to true  the error is: i.LatLng is not a constructor

我已将leaflet.js 添加到页面,因此typeof(L.latlng)"function"latlng 带有小写字母)。

问题:很明显,我从传单中使用的类型在生成 js 文件后无法访问。我的假设是,如果您为任何 js 库创建 ts 声明文件 (.d.ts),则可以在 ts 文件中使用该库。我在这里想念什么?如何在Typescript文件中添加和使用普通js库,使其与webpack捆绑后工作?

【问题讨论】:

    标签: javascript typescript webpack leaflet bundling-and-minification


    【解决方案1】:

    通常的做法是将leaflet 及其关联的@types/leaflet 包安装在您的node_modules 文件夹中,并仅安装import * as L from "leaflet"(或仅安装import L from "leaflet",具体取决于您的webpack 配置)。这些类型将自动可见。而 webpack 会自动打包 Leaflet。

    所有其他 JS 库都一样。

    通过导入类型 (import * as L from './modules/@types/leaflet/index';),你可以告诉 TypeScript L 的含义,而不是 webpack。

    如果出于某种原因您真的想自己添加 Leaflet 库,而不是让 webpack 将其与应用程序的其余部分捆绑在一起,那么您必须告诉 webpack 将 L 保留为是的,因为您将以某种方式在全局范围内提供它。使用externals 配置 webpack,例如:

    module.exports = {
      //...
      externals : {
        "./modules/@types/leaflet/index": {
          root: 'L' // indicates global variable
        }
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2017-06-03
      • 1970-01-01
      • 2016-12-28
      • 2019-07-03
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多