Reputation: 727
I have this api module from outside. When it is installed as a node_module (with npm install), then doing an import like this works:
import MyAPI from 'api'
However, when I look into the api folder in the node_modules and take out the api.js, which is entry point of the module, and do a relative import like this:
import MyAPI from './api.js'
Then I get the error:
"The requested module ./api.js does not provide an export named 'default'"
I have no control over how the api module is built. How can it work in one case but not another? This is Node 12.
Upvotes: 16
Views: 99702
Reputation: 1074505
You've confirmed that the package.json
in the module's folder doesn't have "type": "module"
in it. That's the issue. It's using the older CommonJS system instead of the newer, standard ESM system your module is using. Node.js does some automatic conversion when loading old-style CommonJS modules via ESM (details).
If you want to copy that file out of its module and use it in a different module environment, you'll have to convert its exports (and potentially imports) to ESM. For example, instead of:
exports.example = function example() { };
it would be
export function example() { }
but it's potentially complicated, because the two systems work differently. CommonJS is dynamic, based on property assignment (although the result is static), ESM is static, declarative (although the result is, in some ways, dynamic).
Upvotes: 25