You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中@turf/centroid导入后报错turf未定义,求正确用法

Turf.js模块导入后无法使用的解决方法

问题详情

已在package.json中安装@turf/centroid模块:

{
  "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"
  }
}

在main.js中尝试使用时:

// 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子模块

你安装的是单个Turf子模块而非完整包,不存在全局turf对象,需单独导入每个用到的函数:

  1. 安装并导入featureEach(该函数属于@turf/meta模块):
import centroid from "@turf/centroid";
import featureEach from "@turf/meta";
  1. 替换代码中的turf调用:
const featuresPoint = [];
featureEach(reponse, function (operation) {
  const centroide = centroid(operation);
  const pointCentroid = opeGeoJsonFormat.readFeature(centroide);
  featuresPoint.push(pointCentroid);
  // ...
});

方案二:安装完整Turf包

如果需要使用多个Turf函数,可直接安装完整包:

  1. 执行安装命令:
npm install turf
  1. 导入完整模块:
import * as turf from "turf";

之后就可以像原代码那样用turf.centroid和turf.featureEach调用函数。

内容的提问来源于stack exchange,提问作者Leehan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 15:26:16