【问题标题】:How to use npm package ('latlon-geohash') in angular 7如何在 Angular 7 中使用 npm 包('latlon-geohash')
【发布时间】:2019-07-18 15:08:58
【问题描述】:

我正在尝试在我的 Angular 7 应用程序中使用 latlon-geohash npm 包,但是当我运行它时,我收到了这个错误...

错误类型错误:latlon_geohash__WEBPACK_IMPORTED_MODULE_8__.encode 是 不是函数

这是我的代码:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import * as gh from 'latlon-geohash';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss'],
})
export class AccountComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {
     //Here I'm trying to encode my lat and lng to a GeoHash
    console.log(gh.encode(39.36, -76.69, 4))
  }

}

而且它不起作用。但是,当我运行console.log(gh) 时,我得到了这个...

Module {default: ƒ, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
default: class Geohash
adjacent: ƒ adjacent(geohash, direction)
arguments: (...)
bounds: ƒ bounds(geohash)
caller: (...)
decode: ƒ decode(geohash)
encode: ƒ encode(lat, lon, precision) //HERE IS MY FUNCTION
length: 0
name: "Geohash"
neighbours: ƒ neighbours(geohash)
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: latlon-geohash.js:11
[[Scopes]]: Scopes[3]
Symbol(Symbol.toStringTag): "Module"
__esModule: true
__proto__: Object

我在那里看到了我的encode 函数。为什么它不起作用?我似乎找不到答案,但我觉得我可能缺少一些非常简单的东西。有什么想法吗?

【问题讨论】:

  • 你应该将它添加到 angular.json 中的scripts 数组中。
  • 但是我用npm install latlon-geohash安装了它。我还需要在那里添加它吗?
  • 是的,从Node_modules添加整个路径

标签: javascript node.js angular typescript ecmascript-6


【解决方案1】:

您应该将latlon-geohash 添加到angular.json 内的脚本中。任何第 3 方脚本/库都需要在 scripts 中的 angular.json 中提供。将 latlon-geohash.js 的完整相对路径提供给 Angular 项目,以便它可以使用。

确保您也重建您的项目。

前:

"scripts": [
            "./node_modules/path-to-lib/latlon-geohash.js",

还将导入添加到您的组件:import Geohash from 'latlon-geohash';,正如 Tony 提到的那样。

这里有一个stackblitz link 供您尝试

【讨论】:

  • 当我添加这个时,我得到了这个错误...Error: ENOENT: no such file or directory, open '/node_modules/latlon-geohash⁩/latlon-geohash.js'
  • 我的意思是:检查您的 node_modules 文件夹,找出 latlon-geohash 的路径,打开它到可用的 js 文件,复制它的路径并在脚本中使用该路径 angular .json.
  • 这是正确的道路。我将路径复制并粘贴到 finder 中,它直接进入文件夹。
  • 你是否也使用了`./node_module'并重建了你的项目。
  • 完成!。谢谢:)
【解决方案2】:

试试这2种方法是否有效

import Geohash from 'latlon-geohash';

const Geohash = require('latlon-geohash')

【讨论】:

  • import * as gh from 'latlon-geohash';有什么区别
  • 这是不同的,因为当您使用 import * 时,您会将整个库导入到您不需要的组件中。我们只需要导入我们想要使用的实例
  • 由于库中有export default Geohash;,如果你使用import * as gh,它的工作方式与import Geohash from 'latlon-geohash';相同
  • 您可以使用 webpack-bundle-analyzer 包来查看包大小的不同,其中包含 2 语法导入 * 和普通导入
  • 你是对的,谢谢你的帮助。我还必须将它添加到@nircraft 提到的脚本中
猜你喜欢
  • 1970-01-01
  • 2017-09-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2018-02-15
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多