问题描述
webpack 配置中常见的,当我们需要设置路径时,path.resolve
或 path.join
经常使用,我只是想弄清楚为什么我们必须使用它们而不是普通的字符串路径,例如'../dist'
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.
例如
output: {
filename: '[name].js',
path: path.resolve(__dirname, '../dist'),
chunkFilename: 'js/[name].[chunkhash].js'
}
推荐答案
这与 webpack 无关,只与 Node.js 处理路径的方式有关.默认情况下,路径不是相对于文件路径解析的,而是相对于工作目录解析的.假设我们有以下目录结构:
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
1.js 包含以下内容:
with 1.js containing the following:
const filePath = '../b/2.txt';
const content = require('fs').readFileSync(filePath);
console.log(content.toString());
那么,如果我们运行
cd a
node 1.js
一切正常.
但是,如果我们执行从顶级目录,则如下:
But if, instead we execute from the toplevel directory, the following:
node a/1.js
我们得到一个错误:
Error: ENOENT: no such file or directory, open 'C:\Users\baryl\Desktop\b\2.txt'
因为路径现在是相对于 project
而不是 project/a
解析的.path.resolve 解决了这个问题.
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());
现在我们可以安全地从项目目录中执行node a/1.js
,它会按预期工作.
now we can safely execute node a/1.js
from the project directory, and it will work as expected.
这篇关于为什么 webpack 配置必须使用 path.resolve &路径连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!