DEV Community

Jim Cummins
Jim Cummins

Posted on

5 1

TypeError: Cannot read property 'filename' of undefined in ES Modules in Node 14 and greater

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.

Image of Stellar post

πŸš€ Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay