Must use import to load ES Module
  • 02-May-2023
Lightrun Team
Author Lightrun Team
Share
Must use import to load ES Module

“Must use import to load ES Module” problem

Lightrun Team
Lightrun Team
02-May-2023

Explanation of the problem

The provided error message indicates an issue with importing an ES module in Node.js v12. Specifically, the error message mentions that the module ‘geodesy/latlon-spherical.js’ cannot be loaded with the ‘require’ function because it is an ES module. The error message suggests using the ‘import’ statement instead of ‘require’ to load the module. In Node.js v12, to use the ‘import’ statement, the ‘–experimental-modules’ flag should be enabled. Therefore, the error message may indicate that the flag is not enabled, or the module is not compatible with Node.js v12.

Additionally, the error message suggests that the module ‘geodesy/latlon-spherical.js’ is an ES module and should be loaded using the ‘import’ statement instead of ‘require’. Therefore, the code block should be updated to use the ‘import’ statement, as follows:

import LatLon from 'geodesy/latlon-spherical.js';

const location = new LatLon(50.068, -5.316);

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for “Must use import to load ES Module” problem

As a result, the solution to this problem is to either use a transpiler to convert the ES module code to CommonJS, or to use the –experimental-modules flag to enable ES module support in Node.js.

Enabling ES module support in Node.js requires the –experimental-modules flag to be used when running Node.js. This flag tells Node.js to treat all imported files as ES modules, including the main file that is executed. The flag also enables support for dynamic imports, which are useful for loading modules asynchronously. Once the flag is enabled, ES modules can be imported and used just like CommonJS modules. However, care must be taken to ensure that all imported modules are ES modules and not CommonJS modules, as this can result in errors.

Alternatively, using a transpiler like Babel can also solve the problem of loading ES modules in Node.js. Transpilers convert modern JavaScript code into a backwards-compatible version that can be run in older browsers or environments that do not support modern syntax. By using a transpiler, ES modules can be converted to CommonJS modules, which can be run in Node.js without any issues. The downside of this approach is that it requires an extra build step and may add overhead to the development process, particularly for small projects.

Example code for enabling ES module support in Node.js:

node --experimental-modules myscript.mjs

Example code for using a transpiler to convert ES modules to CommonJS:

// .babelrc
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

// script.js
import { someFunc } from './module.js';
console.log(someFunc());

// module.js
export function someFunc() {
  return 'Hello, world!';
}

Other popular problems with Geodesy

Problem: incompatibility with the ES6 module system

This issue is mainly encountered when using geodesy with Node.js versions 12 and above. The issue arises due to the use of the CommonJS module system, which is not compatible with ES6. Consequently, the user may encounter an error message that reads “Error [ERR_REQUIRE_ESM]: Must use import to load ES Module.”

Solution:

The solution to this problem is to enable ES6 modules when running the Node.js script. To achieve this, the user needs to pass the --experimental-modules flag and the -r esm flag as options when running the Node.js command. This will allow Node.js to support ES6 modules and resolve the incompatibility issue.

$ node --experimental-modules -r esm script.js

Problem: lack of support for some methods in certain scenarios

For example, the LatLonEllipsoidal method of the geodesy library does not support the distanceTo method for points on the antipodal. This issue arises due to the limitations of the Vincenty algorithm, which the method uses. Consequently, the user may encounter an error message that reads “Error: antipodal point.”

Solution:

The solution to this problem is to use an alternative method to compute the distance between points on the antipodal. One such method is the Haversine formula, which can be used as an alternative to the Vincenty algorithm. The user can modify their code to use the Haversine formula when working with antipodal points to avoid the error.

// Using Haversine formula for antipodal points
if (p1.isAntipodalTo(p2)) {
    const lat = Math.abs(p1.lat + p2.lat) / 2;
    const dLat = Math.abs(p1.lat - p2.lat);
    const dLon = Math.abs(p1.lon - p2.lon);
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(p1.lat) * Math.cos(p2.lat) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const d = ellipsoid.a * c;
    return new Distance(d, 0, 0);
} else {
    // Using Vincenty algorithm for non-antipodal points
    const result = p1.distanceTo(p2);
    return result;
}

Problem: inconsistency in units between different methods

For example, the geodesy.LatLonEllipsoidal.distanceTo method returns the distance between two points in meters, while the geodesy.Utm.forward method returns the easting and northing values in kilometers. This inconsistency can cause issues when using the values from one method in another method, leading to incorrect results.

Solution:

The solution to this problem is to convert the units to a common unit before using them in another method. For example, if the user needs to use the easting and northing values returned by the geodesy.Utm.forward method in the geodesy.LatLonEllipsoidal.distanceTo method, they can convert the values from kilometers to meters before passing them as arguments to the method.

A brief introduction to Geodesy

Geodesy is a JavaScript library that provides tools for performing various geodetic calculations. The library supports calculations for different shapes of the earth and provides a range of functions for converting between different coordinate systems, calculating distances, bearings, and other geodetic quantities. The library also includes support for geodetic curves, such as the geodesic and rhumb line, and provides tools for working with vector quantities like velocity and acceleration.

Geodesy is implemented as a collection of classes and functions that are designed to be easy to use and highly flexible. The library is written in a modular style, making it easy to include only the functionality that is needed for a particular application. The library is also designed to be highly accurate, using precise algorithms and taking into account the latest geodetic data and models for the shape of the earth. Overall, Geodesy is a powerful and reliable tool for performing geodetic calculations in JavaScript applications.

 

Most popular use cases for Geodesy

1. Geodesy can be used for calculating geographic positions and distances between points on the Earth’s surface. For example, the following code block demonstrates how to use the Geodesy library to calculate the distance between two points in kilometers:

const { LatLonEllipsoidal, Dms } = require('geodesy');

const point1 = new LatLonEllipsoidal(new Dms(52, 12, 13.8, 'N'), new Dms(0, 8, 26.3, 'W'));
const point2 = new LatLonEllipsoidal(new Dms(51, 30, 16.8, 'N'), new Dms(0, 7, 29.6, 'W'));
const distance = point1.distanceTo(point2) / 1000; // in kilometers
console.log(distance);

This code block imports the LatLonEllipsoidal and Dms classes from the Geodesy library and creates two points on the Earth’s surface with latitude and longitude coordinates. Then, it calculates the distance between the two points in kilometers using the distanceTo method and outputs the result to the console.

 

2. Geodesy can be used for converting between different geographic coordinate systems. For example, the following code block demonstrates how to use the Geodesy library to convert a point from the WGS84 coordinate system to the UTM coordinate system:

const { Utm, LatLon } = require('geodesy');

const point = new LatLon(51.5074, -0.1278); // London, UK
const utmCoords = Utm.fromLatLon(point);
console.log(utmCoords);

This code block imports the Utm and LatLon classes from the Geodesy library and creates a point with latitude and longitude coordinates for London, UK. Then, it uses the fromLatLon method of the Utm class to convert the point to the UTM coordinate system and outputs the result to the console.

 

3. Geodesy can be used for performing complex geodetic calculations, such as determining the intersection point between two lines on the Earth’s surface. For example, the following code block demonstrates how to use the Geodesy library to calculate the intersection point between two lines:

const { LatLonEllipsoidal, Vector3d } = require('geodesy');

const point1 = new LatLonEllipsoidal(37.771008, -122.41175);
const bearing1 = 116.45;
const point2 = new LatLonEllipsoidal(37.774188, -122.414323);
const bearing2 = 56.5;

const intersection = point1.intersection(point2, new Vector3d(bearing1, bearing2));
console.log(intersection);

This code block imports the LatLonEllipsoidal and Vector3d classes from the Geodesy library and creates two points on the Earth’s surface with latitude and longitude coordinates, as well as bearings. Then, it uses the intersection method of the LatLonEllipsoidal class to calculate the intersection point between the two lines and outputs the result to the console.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.