Javascript - 如何在 Node.js 中使用导入的模块

问题描述 投票:0回答:1

这是我的

package.json

"name": "api_geoservices",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "node test.js"
},
"devDependencies": {
"vite": "^4.0.4"
},
"dependencies": {
"@turf/centroid": "^6.5.0",
"ol": "latest",
"ol-ext": "^4.0.13",
"proj4": "^2.9.2"
 }
}

可以看到centroid模块已经安装了。

在 main.js 中,我正在使用

centroid
模块,如下所示:

*imports*
import centroid from "@turf/centroid"
...
const featuresPoint = []
turf.featureEach(reponse, function (operation) {
  const centroide = turf.centroid(operation)
  const pointCentroid = opeGeoJsonFormat.readFeature(centroide)
  featuresPoint.push(pointCentroid)
....
})

在浏览器中,控制台注销

Uncaught (in promise) ReferenceError: turf is not defined
。看来
turf
不是全局变量。美好的。那么如何正确使用导入的模块而不是在html文件中使用cdn链接呢?我看不到我在 doc

中错过的内容
import es6-modules
1个回答
0
投票

您使用:

turf.featureEach & turf.centroid

但是您导入了质心:

import centroid from "@turf/centroid"

详细解释:

  • 强调直接导入:“您已直接从

    centroid
    模块导入了
    @turf/centroid
    函数。这意味着您可以在没有
    turf.
    前缀的情况下使用它。”

  • 用法示例:

    const centroide = centroid(operation); // Using the imported 'centroid' 
    
© www.soinside.com 2019 - 2024. All rights reserved.