Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use __dirname along with path.resolve in webpack config?

I was going though this webpack tutorial: https://youtu.be/TOb1c39m64A

At around 1:30:00 mark he discusses the use of __dirname in path.resolve however I don't quite understand what's the difference between using and not using it.

Dont they both (path.resolve & __dirname) mean the same thing? Both give the current absolute directory where this file is running. This is confirmed by the fact that when I remove __dirname it still creates the build files at same root location (even if the webpack.config.js) file is not present at the root level. i.e. both the below codes yield same result:

With __dirname

  output: {
    assetModuleFilename: "images/[hash][ext][query]",
    path: path.resolve(__dirname, 'dist')
  }, 

Without __dirname:

  output: {
    assetModuleFilename: "images/[hash][ext][query]",
    path: path.resolve('dist')
  }, 

So what is the need to use __dirname here??

like image 235
D_S_X Avatar asked Mar 02 '23 11:03

D_S_X


1 Answers

You have right in your scenario they will work in same fashion.

But there is a subtle difference between those two, and I will try to explain it.

__dirname in Node script will give you absolute path of the where current JS file resides.

path.resolve on the other hand gives you absolute path which if not constructed from path segments, defaults to current working directory. (which is your situation).

There is difference between path of where js file resides and currently working directory.

How you can find this difference? In your app you can change current directory using: processs.chdir(./example).

Now if you check your addresses they won't be same. path.resolve will also append this /example part in yours path. __dirname will still reference on the right path.

Shortly in your case they will work exactly same, but __dirname is more robust approach.

like image 108
Predrag Davidovic Avatar answered Mar 07 '23 18:03

Predrag Davidovic