DEV Community

Kemal Ahmed
Kemal Ahmed

Posted on

How to use Babel's new addExternalDependency API

The story begins with me as a clout-chasing, NPM library maintainer. The library is a Babel plugin, known as react-native-dotenv.

The problem? Babel was caching the non-Javascript files the library was meant to load. The real problem? My ego was being obliterated by developers who were replacing my library as a dependency because they needed a functional way to load environment variables into their react native apps.

To solve it, I scoured the Babel feature pipeline, a.k.a. random draft PRs people had created to add any file to the Babel watchlist. I bumped it, did no extra work, watched the Babel team pick it up and do an epic job on it, and planned to write a blog to take full credit for my prod.

When addExternalDependency was born, the release had so many other amazing features, the docs were not up to par of the other Babel docs. So I made a pact with the devs that I would write some documentation in exchange for help on fixing up my library and this is my lousy attempt at it.

So to begin, in my module.exports function, I made sure to tell Babel what and how to cache the alien files that are dear to my library. I use a function to verify if they've been updated recently

function mtime(filePath) {
  try {
    return statSync(filePath).mtimeMs
  } catch {
    return null
  }
}
Enter fullscreen mode Exit fullscreen mode

and for each file path I'm checking I add:

api.cache.using(() => mtime(options.path))
Enter fullscreen mode Exit fullscreen mode

Now we tell Babel to watch for changes and recompile:

api.addExternalDependency(path.resolve(options.path))
Enter fullscreen mode Exit fullscreen mode

And for the hardest part? Convince every library to upgrade their versions of Babel. Or tell your users to add the following to their package.json:

"resolutions": {
  "@babel/core": "^7.20.2",
  "babel-loader": "8.3.0"
}
Enter fullscreen mode Exit fullscreen mode

As of writing this article I am searching for a job. If I've tricked you into thinking I'm a half-decent Javascript developer, please tell a hiring manager near you because I'm competing against other exceptional devs from Twitter and Meta.

Top comments (1)

Collapse
 
pierregambaud profile image
Pierre Gambaud

Thanks a lot Kemal!

Adding the following to my package.json solved my "api.addExternalDependency is not a function" error:

"resolutions": {
  "@babel/core": "^7.20.2",
  "babel-loader": "8.3.0"
}
Enter fullscreen mode Exit fullscreen mode