I was surprised by an experience with relative paths in JavaScript today. I’ve boiled down the situation to the following:
Suppose you have a directory structure like:
app/
|
+--app.html
+--js/
|
+--app.js
+--data.json
All my app.html
does is run js/app.js
<!DOCTYPE html>
<title>app.html</title>
<body>
<script src=js/app.js></script>
</body>
app.js
loads the JSON file and sticks it at the beginning of body
:
// js/app.js
fetch('js/data.json') // <-- this path surprises me
.then(response => response.json())
.then(data => app.data = data)
The data is valid JSON, just a string:
"Hello World"
This is a pretty minimal usage of fetch
, but I am surprised that the URL that I pass to fetch
has to be relative to app.html
instead of relative to app.js
. I would expect this path to work, since data.json
and app.js
are in the same directory (js/
):
fetch('data.json') // nope
Is there an explanation for why this is the case?
fetch(import.meta.resolve("./data.json"))"
if you are using CommonJS ("require" package from npm):fetch(require.resolve("./data.json"))
– Victualer