' L'引用UMD全局 - 编译错误

时间:2017-09-07 09:30:37

标签: angular typescript webpack angular-cli ngx-leaflet

我在我的项目中使用了插件ngx-leafletangular-cli

我正在尝试使用文档中描述的传单,例如:

enter image description here

问题是当我尝试编译时出现以下错误:

enter image description here

编译:

ng serve --aot

上下文:

enter image description here

我尝试使用以下方式以不同方式导入L

import { LeafletModule } from '@asymmetrik/ngx-leaflet';

但我在文档中找不到任何内容,也没有找到github

我确实删除了模块atm进行编译,但我需要一个解决方法。

以下是我使用的package.json

enter image description here

以下是我的组件中的代码,'L'的用户:

@Component({
  selector: 'app-map-screens-element',
  templateUrl: './map-screens-element.component.html',
  styleUrls: [
    './map-screens-element.component.scss',
  ],
})

export class MapScreensComponent implements OnInit {
  /**
   * setting map options
   */
  public $mapOptions = {
    // we use the layer openstreetmap
    layers: [
      L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'),
    ],
    zoom: 15,
    center: L.latLng([48.866667, 2.333333]),
  };
}

这里将模块导入我的项目:

import { LeafletModule } from '@asymmetrik/ngx-leaflet';

@NgModule({
  imports: [
    LeafletModule,
  ],
  declarations: [
    // ...
  ],
  exports: [
    // ...
  ],
})

export class SharedElementModule { }

2 个答案:

答案 0 :(得分:20)

您在组件顶部缺少L的导入。像这样:

import * as L from 'leaflet';

答案 1 :(得分:0)

After cloning the angular-cli into a new empty project I added sockjs-client via NPM. Then I tried to create a SockJS instance in an NG-Service like so. SockJs is just a sample for a none angular compliant npm package:

import { SockJS } from 'sockjs-client';
//...
private socket: SockJs;
//...
this.socket = new SockJS(this.serverURI);

This compiled fine but had a runtime error stating

SockJS is not a constructor

After some googling I stumbled over typings in angular to make js-types available to the typescript transpiler https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. To make it work I had to add types by installing @types/sockjs-client from NPM. That delivered the compiler error

'SockJS' refers to a UMD global, but the current file is a module. Consider adding an import instead.

This error means that the types are known to typescript transpiler but not explicitly imported. You have to import the types to explicitly tell typescript that you know you are using an external script whose existence can not be verified by typescript while compiling. The presence of that package will only be checked during runtime. The explicit import statement looks like this

import * as SockJsClient from 'sockjs-client';
//...
private socket: SockJsClient.Socket;
//...
this.socket = new SockJsClient(this.serverURI);