Angular 2 - 引入外部的 Leaflet TypeScript 库

4

我正在尝试将一个typescript的leaflet库导入到我的angular 2应用程序中。

这是我的地图组件。我已经使用tsd install安装了leaflet.d.ts,并且我的应用程序没有抱怨/// <reference path="../../typings/leaflet/leaflet.d.ts"/>,但是当我尝试使用在leaflet.d.ts中导出的L.map时,我会收到错误信息“ReferenceError: L is not defined”。这是我第一次在angular 2中导入外部typescript库,显然我做错了什么。

/// <reference path="../../typings/leaflet/leaflet.d.ts"/>
import { Component } from 'angular2/core';
@Component({
  selector: 'map',
  template: `
        <div id="map"></div>
  `,
})
export class Map{
    constructor(){
          var map = new L.Map('map', {
             zoomControl: false
         });
    }

package.json

{
  "dependencies": {
    "angular2": "^2.0.0-beta.3",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "normalize.css": "^3.0.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "systemjs": "0.19.6",
    "typings": "^0.6.4",
    "zone.js": "^0.5.11"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "gh-pages": "^0.11.0",
    "grunt": "~0.4.5",
    "grunt-contrib-clean": "^1.0.0",
    "grunt-contrib-copy": "^1.0.0",
    "grunt-contrib-cssmin": "^1.0.0",
    "grunt-contrib-nodeunit": "~0.4.1",
    "grunt-contrib-sass": "~0.9.0",
    "grunt-contrib-uglify": "~0.5.0",
    "grunt-shell": "^1.2.1",
    "lite-server": "^2.0.1",
    "normalize.css": "^3.0.3",
    "typescript": "^1.7.5"
  },
  "scripts": {
    "publish": "node publish.js",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  }
}

tsd.json

{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "leaflet/leaflet.d.ts": {
      "commit": "1da639a106527e0c4010b354a1efe52a3059a291"
    }
  }
}

有人能告诉我我做错了什么吗?

谢谢!


我相信你也需要将leaflet.js连接到你的页面上。d.ts文件仅用于告诉TypeScript一些JS代码,d.ts不会导入实际的代码。 - Kostya Shkryob
好的。我已经将leaflet js文件放在我的项目文件夹中。你知道我该如何将我的ts文件连接到这个文件夹吗? - Jakob Svenningsson
如果需要的话,您可以使用<script>标签或依赖管理器。 - Kostya Shkryob
4个回答

4

您需要包含leaflet JS文件:

System.config({
  map: {
    leaflet: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js'
  },
  packages: {'app': {defaultExtension: 'ts'}} 
});
System.import('app/main')
        .then(null, console.error.bind(console));

那么您可以这样在模块中导入它:
import {Component, OnInit} from 'angular2/core';
import leaflet from 'leaflet';

请查看此plunkr:http://plnkr.co/edit/aUo2uvlxC5ji32u01jfF?p=preview


2
我该如何将它添加到我的angular-cli配置文件中?我已经按照您提到的在系统配置中添加了,但是导入leaflet时找不到模块。 - Emu
同意。想了解如何使用angular-cli和webpack。 - BBaysinger

3

我可以给你提供一个解决方法,直到angular-cli更好地支持第三方库。这个方法对我有用 :)

首先进入项目目录并输入以下命令:

npm install leaflet --save

然后打开你的angular-cli-build.js文件并添加这一行

vendorNpmFiles: [
   ..................
   'leaflet/**/*.js',
    ....................
  ]

现在打开您的src/system-config.ts文件,编写:
const map:any ={
     ..................
   'leaflet': 'vendor/leaflet/dist',
    ....................

}

并且

const packages: any = {
  'leaflet': {
    format: 'cjs'
  }

};

打开 src/index.html 文件,添加以下内容。
 <script type="text/javascript" src="vendor/leaflet/dist/leaflet.js"></script>

别忘了也要添加CSS文件。

  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />

现在打开您想要使用Leaflet的组件。
declare let L: any;
@Component({
  moduleId: module.id,
  selector: 'app-map',
  templateUrl: 'map.component.html',
  styleUrls: ['map.component.css']
})
export class MapComponent implements OnInit, AfterViewInit {
 leafletMap: any;
 ngAfterViewInit() {
    this.leafletMap = L.map("map").setView([23.709921, 90.407143], 7);
 }
}

塔达!您的地图已加载:D


我猜你想在地图数组中写入'leaflet': 'vendor/leaflet/dist',对吗? - Sobvan

2

为了让Thierry Templier的答案在使用systemjs和Angular 2.4时能够工作,我不得不做出一些更改。

我按照他所说的方式将Leaflet添加到我的 system.config.js 文件中,但是在我的组件中,我必须以这种方式导入它:

import * as L from 'leaflet';

然后L类就被我的MapComponent识别了。

export class MapComponent {
    let map = L.map("map").setView([38, -77], 13);
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
    }

2

同时,你需要做的只是调用

npm install @types/leaflet@latest --save

包括在index.html中的源代码。

不需要其他导入或声明。然后,导入可以看起来像

import {control, LatLng, layerGroup, LayerGroup, Map} from "leaflet";

同样地,地图初始化应在ngOnInit()中进行,构造函数的使用不适用于逻辑处理。

这应该是--save-dev吗? - chrismarx
@chrismarx 我不知道,它应该吗?它不是开发工具,而是实际的应用程序代码,所以我猜不应该。 - phil294
1
嗯,类型只在开发过程中有用,类型在转译过程中会消失。 - chrismarx
使用Angular CLI时,我仍然需要添加declare var L: any;或者ng serve会打印出Cannot find name 'L' - 我是否漏掉了什么? - schellmax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接