sanjar-notes / frontend

The basics - HTML, CSS, Javascript, browser APIs, performance
3 stars 0 forks source link

Using JSON files in vanilla websites #102

Open sanjarcode opened 1 year ago

sanjarcode commented 1 year 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 1 year ago

Related:

sanjarcode commented 9 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