geojson-path-finder: distance is not a function

Can you help with resolving this? Not sure what the issue is.

TypeError: distance is not a function9 | module.exports = function preprocess(graph, options) { 10 | options = options || {}; 11 | var weightFn = options.weightFn || function defaultWeightFn(a, b) { 12 | return distance(point(a), point(b)); 13 | }, 14 | topo; 15 |

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (2 by maintainers)

Most upvoted comments

Actually it does works with create-react-app in the browser. The issue is with require function which behaves differently in webpack.

Changing one line in src/geojson-path-finder/preprocessor.js from

 distance = require('@turf/distance'),

to

 distance = require('@turf/distance').default,

does make is work with webpack, and paths can be found now on frontend as well.

Im assuming that this could be fixed in webpack.config

You’re right, the problem isn’t with geojson-path-finder, or Turf, it’s with Webpack. But as far as I can work out, it can only be fixed with changes to each user’s Webpack config, or a change to how geojson-path-finder imports.

The problem: @turf/distance contains two files with the same logic, one in es6 module style (main.es.js), and a commonjs one too (main.js). Webpack, annoyingly, picks the es module unless you specify otherwise in your config.

What geojson-path-finder can do in order to work with Webpack is to explicitly say that it wants to use the commonjs version, with:

var distance = require('@turf/distance/main') // use /main to ensure the commonjs file is used

Adding .default as suggested above does something slightly different, and uses the es6 version but targets the default export.

P.S. there’s a much more involved fix of making this package ES6 and compiling it to ES5 with Webpack.

Qunabu, I love you. Thank you so much.