The problem
When importing a Node.js module that uses some code similar to the following code:
module.parent.filename
You might get an error similar to the following:
TypeError: Cannot read property 'filename' of undefined.
The error can seem cryptic and might make you think there is a problem with the module you are importing. As it turns out, the problem is that you are using ES Modules in Node 14+ and using import
to load a CommonJS module. While using this import
syntax may sometimes work with CommonJS, some will not.
Luckily with a quick change you can successfully import the CommonJS module while still using import
and ES Modules for the rest of your app/library.
Why it happens
module.parent simply doesn't exist in Node ES Modules. It was removed because ES Modules are not a tree, but rather a graph. Thus the word 'parent' doesn't actually make sense when thinking about the module structures. Instead of thinking about hierarchy we're just at a point in a graph. Anyhow you don't need to worry about this distinction if you just fix this error.
A solution
Instead of using the following code to import the module called meow:
import meow from "meow";
You can use the following code to import the meow module:
import { createRequire } from "module";
const meow = createRequire(import.meta.url)("meow");
This is simply a way to tell Node to use the older require / CommonJS module loading while inside an ES Module. When you do this, module.parent.filename will be available again for the subtree of modules that get loaded.
Special thanks to Myles Borins for his input on solving this.
Top comments (0)