What does this __dirname even mean?
You might have seen this guy __dirname
a couple of times, maybe in a webpack config like this
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
Well, but what is __dirname
?
It is a variable that is accessible in every javascript module(or file), and its value is the absolute path of the immediate parent directory in which the file is located. Let's first see what is absolute
and relative
paths are.
Folder structure for Demonstration
my-app
|___ src
|___ utils.js
|___ helpers.js
|___ index.js
|___ package.json
Absolute Path
absolute
path is the complete information you need to get to your destination.- It locates your destination by considering the
root
folder of your operating system as a reference. - By following the
absolute
path you will always reach the correct destination, hence the nameabsolute
- Example, for the above folder structure, the
absolute
path formy-app
directory would beC:\Users\SAIRAJ\Desktop\my-app
in windows/home/sairaj/my-app
in Linux
Relative path
- Instead of considering the
root
directory of your operating system as a reference to locate your destination, it considers some other directory as its reference - Example, in the above folder structure
- relative path for
utils.js
considering reference directory asmy-app
would be./src/utils.js
- Relative path for
index.js
considering reference directory assrc
would be../index.js
(..
two dots refer to go back one directory and since we are considering reference directory assrc
we have to go back one directory to reachindex.js
)
- relative path for
Understanding __dirname
if we recall the definition of __dirname
it stores the absolute path of the immediate parent directory the file is located in, so lets console.log(__dirname)
in each of utils.js
, helpers.js
, and index.js
The logs are
/home/sairaj/my-app
forindex.js
/home/sairaj/my-app/src
forutils.js
andhelpers.js
As we know the parent directory of index.js
is my-app
, and utils.js
, helpers.js
is src
, we got the expected absolute paths for them.
NOW that we understood what __dirname
is and what it stores in it, we can ask a question, why do I care about __dirname
, why should I use it? the answer is simple, to get the path of our destination that can be used flawlessly, as we have seen the webpack
config at the staring of the article, the output
object uses __dirname
to correctly locate the output
directory for the compiled code, and since the path is absolute
there is no confusion about the destination that it leads to.
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
Once again, __dirname
stores the value of absolute
path of the immediate parent directory
of the file in which we used __dirname