最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why webpack config has to use path.resolve & path.join - Stack Overflow

programmeradmin7浏览0评论

It is mon 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'
}

It is mon 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'
}
Share Improve this question asked Jan 20, 2018 at 8:54 Deng ZhebinDeng Zhebin 1,2621 gold badge10 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 21

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.

发布评论

评论列表(0)

  1. 暂无评论