Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why webpack config has to use path.resolve & path.join

It is common seen in webpack configuration that when we need to set the path ,path.resolve or path.join are often used , I just want to figure out why we have to use them instead of a plain string path e.g. '../dist'

I partly understand maybe for some purpose , they are used to return the absolute path ,but I think the plain string path is able to function as well.

e.g

output: {
filename: '[name].js',
path: path.resolve(__dirname, '../dist'),
chunkFilename: 'js/[name].[chunkhash].js'
}
like image 662
Deng Zhebin Avatar asked Jan 20 '18 08:01

Deng Zhebin


1 Answers

This has nothing to do with webpack, only with the way Node.js handles paths. Paths are not resolved relative to the file path, but relative to the working directory by default. Say we have the following directory structure:

project
 ├── a
 |   └── 1.js
 └── b
     └── 2.txt

with 1.js containing the following:

const filePath = '../b/2.txt';
const content = require('fs').readFileSync(filePath);
console.log(content.toString());

then, if we run

cd a
node 1.js

everything works fine.

But if, instead we execute from the toplevel directory, the following:

node a/1.js

we get an error:

Error: ENOENT: no such file or directory, open 'C:\Users\baryl\Desktop\b\2.txt'

because the path is now resolved relative to project instead of project/a. path.resolve solves that.

const path = require('path');
const filePath = path.resolve(__dirname, '../b/2.txt');
const content = require('fs').readFileSync(filePath);
console.log(content.toString());

now we can safely execute node a/1.js from the project directory, and it will work as expected.

like image 194
Bary12 Avatar answered Sep 18 '22 09:09

Bary12