javascripthtmljsonmodulescript-tag

Adding a Script to HTML returns errors


I have this script 'a.js':

import * as assets from '../assets/b.json';

async function loadData() {
  ...
}

b.json:

[
  {...},
  {...}
]

I try to add this Script to my HTML but I get this error when I put type="module".

<script type="module" src="../scripts/a.js"></script>

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

And when I don't put type="module" I get this error

<script src="../scripts/a.js"></script>

Uncaught SyntaxError: Cannot use import statement outside a module

I've been stuck on this error for a while and I don't know what to do.


Solution

  • import * as assets from '../assets/b.json';
    

    It looks like there are two issues here.

    1. The server says this is HTML so either:
      • Your URL is wrong (this is most likely and you should debug it by using the Network tab of the browser's developer tools to see what body and Content-Type header are on the response)
      • Your server is configured to claim that .json files are HTML and not JSON
    2. Support for JSON modules in web browsers is very weak.
      • Not supported in Chrome in 2022
      • Not supported in Firefox in 2022
      • Not supported in Safari in 2022