turf icon indicating copy to clipboard operation
turf copied to clipboard

How to properly import turf on TypeScript?

Open yukha-dw opened this issue 3 years ago • 5 comments

Hello, I'm stumbled weird error on TypeScript. Despite lint tells me turf.geometry() is a valid function, I get TypeError: Cannot read property 'geometry' of undefined when calling it. Is there anything I can do about it?

tsconfig

"target": "ES2020"
"module": "commonjs"
"lib": ["ES2020"]

example

// Error
import turf from '@turf/turf';
turf.geometry('Point', [20, 20])

// Safe
import { geometry } from '@turf/helpers';
geometry('Point', [20, 20])

yukha-dw avatar Jul 26 '22 08:07 yukha-dw

@turf/turf does not have a default export so import turf from '@turf/turf'; is incorrect. You should do this instead import * as turf from '@turf/turf';. Then you can access all the turf functions like: turf.geometry, turf.point etc.

robinsummerhill avatar Aug 04 '22 07:08 robinsummerhill

@turf/turf does not have a default export so import turf from '@turf/turf'; is incorrect. You should do this instead import * as turf from '@turf/turf';. Then you can access all the turf functions like: turf.geometry, turf.point etc.

Thank you so much, i genuinely thought turf has default export.

yukha-dw avatar Aug 04 '22 07:08 yukha-dw

I think this should be shown in the docs

stebogit avatar Aug 04 '22 13:08 stebogit

I have built a build environment that allows me to easily start "Turf.js" with a combination of "MapLibre GL JS," "Vite," and "TypeScript." https://github.com/dayjournal/turfjs-starter

dayjournal avatar Oct 01 '22 14:10 dayjournal

I think this is already shown in the docs: http://turfjs.org/getting-started - there's an example of importing all of turf using * as turf.

tmcw avatar Nov 09 '22 14:11 tmcw