路徑解析:path.resolve([from ...], to)
學習 webpack 遇到 path.resolve 但文檔讀完一遍很懵圈;
網上搜到一篇比較有用的文章 https://blog.csdn.net/kikyou_csdn/article/details/83150538
同時也給出了 join 連接路徑和 resolve 路徑解析的不同 :https://www.cnblogs.com/moqiutao/p/8523955.html
這篇文章中有個比較好理解的觀點就是 把 resolve 想象成 cd 命令。這樣就容易理解了:
path.resolve()方法可以將多個路徑解析為一個規范化的絕對路徑。其處理方式類似於對這些路徑逐一進行 cd 操作,與 cd 操作不同的是,這引起路徑可以是文件,並且可不必實際存在(resolve()方法不會利用底層的文件系統判斷路徑是否存在,而只是進行路徑字符串操作)。例如:
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
相當於
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
例子:
path.resolve('/foo/bar', './baz')
// 輸出結果為
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// 輸出結果為
'/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// 當前的工作路徑是 /home/itbilu/node,則輸出結果為
'/home/itbilu/node/wwwroot/static_files/gif/image.gif'
總結
-
./ 和目錄名前面什么都不加代表當前目錄下執行 cd
-
/ 表示根目錄下執行 cd
-
所以要判斷最后出來的是根目錄還是當前工作目錄看第一個參數的目錄名前面是/ 還是 ./和什么都沒加