Use webpack with __dirname correctly
While working on server-side code, I used webpack to compile some of my JavaScript files. I came upon an error where I had webpack compiled code acting differently than webpack un-compiled code.
The root of the issue was how webpack handled Node variables such as
__dirname
.
__dirname
returns the the directory name of the current module. Let’s take a look at some code that uses __dirname
.

This is what the output of it looks like.

Now let’s take at look at similar code that uses webpack.

This is what the output of it looks like.

Notice how the __dirname
is different depending on whether you use webpack or not. This is because webpack replaces __dirname
with /
. It’s a weird default and might cause some hard-to-find bugs. It also does this with __filename
.
To have the __dirname
act the same when getting compiled by webpack, we can update our webpack configuration like so.

See the webpack documentation for more details.
Other Lessons learned
If you are using webpack only to use Babel to compile your server-side code, there is an alternative. Instead of using webpack, you may be able to use babel-register
. (Disclaimer: using babel-register
compiles your code at runtime, rather at build time. This results in greater server processing time)

Note that you might still need webpack if using other loaders (besides Babel) or plugins.