Incompatibility of ES and CommonJS Modules Causes This Error
The most probable cause of this exception is inconsistency of syntaxes of ES and CommonJS modules. Using different syntax conventions in the same module can lead to conflicts resulting in syntax errors and runtime errors. I, for example, encountered this error (Chrome browser):
Uncaught SyntaxError: The requested module '/node_modules/axios/index.js?v=fae0673e' does not provide an export named 'default' (at index.ts:1:8)
In Firefox, the error text is as follows:
Uncaught SyntaxError: ambiguous indirect export: default
In 2023, you're most likely using ES syntax, but the libraries you're plugging in are most likely distributed in CommonJS syntax.
To determine the syntax:
- look in
package.json
and check the module
and main
fields: if there is a file there with the extension .mjs
or .js
, this indicates the ES module format;
- if the
main
field points to a file with .cjs
extension (or the file uses require syntax), it points to the CommonJS format.
In my case, the error pointed to the following line:
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
I knew I was using ES6, but was unsure about axios 0.27.2. Opening its package.json
,
I found the "main": "index.js"
property, but inside the file itself I saw CommonJS syntax:
module.exports = require('./lib/axios');
The require meant that I was trying to import a CommonJS module from my ES module, which caused the error.
Solution
The solution was pretty simple: upgrade axios to version 1.4.0, where the library uses ES syntax by default and CommonJS provides on-demand:
npm i axios@latest
Another possible solution
import * as axios from "axios";
const defaultExport = axios.default;
First we import all exported values from "axios" module and pack them into one object named "axios", and then we access the default exported variable.
You can also consult MDN for detailed help on imports.