Absolute Path & Relative Path

Alex Yin
4 min readFeb 13, 2022

--

繼上一篇What is URL?整理了關於url的構造,這篇我想要來講講Absolute Path與Relative Path。

Photo by Remotar Jobs on Unsplash

What is Path?

首先,這裡所指的Path(路徑),即是我們在url裡所指的path to file

A file path describes the location of a file in a web site’s folder structure.

也就是說,在網頁結構底下,我要找到該網頁內的某一網頁、圖片、資料,由此root網頁一路尋找到該資料的路徑,即是path。

以上一篇文章What is URL?的url為例:

https://medium.com/@alexyin0978/what-is-url-86f2233c096d

這個url的root即為medium.com,而指向文章"What is URL?"的path則是

/@alexyin0978(作者帳號)/what-is-url-86f2233c096d(該文章)

斜線/代表「前往」該檔案(資料夾)

而Path的形式分為兩種,第一種為Absolute Path,第二種為Relative Path

Absolute Path

An absolute file path is the full URL to a file

URL即是這種形式,會完整的將要到達該目標資料的路徑,從root一路寫出來,見此範例:

root(domain)/path1/path2/file

而有時,我們會省略root的名稱,直接以

/path1/path2/file

呈現,這種也是absolute path的一種。

Relative Path

A relative file path points to a file relative to the current page.

相對於absolute path將所有到達目標資料的路徑完完整整的交代清楚,relative path顯示的則是以「目前」位置到達該「資料」的路徑。這種相對路徑寫法,比較常用在從「檔案a」置入另一「檔案b」時。

舉例,今天有一資料夾src,裡頭有另外兩個資料夾folder1與folder2,在folder1裡面有script1.js與script2.js,在folder2裡面則有otherScript.js

src/
folder1/
script1.js、script2.js
folder2/
otherScript.js

現在我們來看看各種置入(import)檔案時,relative path的寫法:

假設我們開啟script1.js,並要在這檔案內另外import進script2.js與otherScript.js這兩個檔案:

import script2 from './script2.js'import otherScript from '../folder2/otherScript.js

在這裡,一個點’.’代表的是目前所在位置;兩個點’..’代表回到上一層資料夾

今天若皆以absolute path的方式去寫路徑,則會長這個樣子:

//If the root is: "http://localhost:3000/"import script2 from '/src/folder1/script2.js'import otherScript from '/src/folder2/otherScript.js

那麼,該使用哪一種path寫法比較好?

It is best practice to use relative file paths (if possible). When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.

除了網頁url是用absolute path之外,一般在寫code時,要置入另一檔案,會建議使用relative path,如此才可以避免當檔案上傳到另一個電腦運作(heroku、github等),不會因為domain更換 造成底下檔案找不到path的情況。

參考資料:

  1. HTML File Paths
  2. Absolute vs. Relative Paths

--

--

Alex Yin

1997年誕生 / 建築系畢業 / 古蹟迷 / 自學寫網頁程式 / 努力當個很酷的人!Github page: github.com/alexyin0978