sanjar-notes / web_dev_fundamentals

The basics - HTML, CSS, Javascript and more
https://sanjar-notes.github.io/web_dev_fundamentals/
3 stars 0 forks source link

Using JSON files in vanilla websites #102

Open sanjarcode opened 10 months ago

sanjarcode commented 10 months ago
  1. Node - require works. import works too, but might need assert JSON.
  2. Browser (vanilla) - fetch('./path-to-file') is simplest way that works for all browsers. FYI, import (with assert JSON) works on Chrome, but fails on Firefox or Safari.
  3. Browser with bundlers - import data from "data.json" works fine.

On web, prefer using this wrapper

async function fetchJSON(pathToFile) {
  const resp = await fetch(pathToFile);
  const jsonFileAsObject = await resp.json();
  return jsonFileAsObject;
}
sanjarcode commented 10 months ago

Related:

sanjarcode commented 6 months ago

A more specific proposal of the above is in place to solve this. Will be released in 2024 hopefully. Current support is almost zero. See

Syntax is the same, with