Failed to load module script because of a disallowed MIME type
Asked Answered
M

2

11

Consider the following file structure and content:

js
└─ test
    ├─ modules
    │  └─ math.mjs
    └─ main.mjs

math.mjs:

export function square(v) { return v * v; }

main.mjs:

import { square } from './modules/math.mjs';
console.log(square(2));

On a simple page at http://server.local/module-test (through Apache web server), I'm trying to load the main.mjs:

<script type="module" src="http://server.local/js/test/main.mjs"></script>

but the browsers keep complaining about the MIME type, for example:

Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

I've tried other relative-references (through /, ./ and ../) on the import statement to no avail!

So, what I've missed to have it working?

Moresque answered 4/1, 2020 at 19:21 Comment(1)
Configure the server to serve .mjs files with an appropriate javascript MIME type, or simply try using .js file extension.Clunk
B
4

One of the conditions for a module to be loaded by the browser is that the server serves the module with a MIME type of application/javascript (or other appropriate MIME type depending on language and browser support; there's a new type javascript/esm for javascript modules that has mixed support). This means configuring the server provide a response header that includes at least Content-Type: application/javascript for javascript modules (or javascript in general).

From the error you're getting, it seems your server is either providing an empty Content-Type header or not providing it at all. This usually happens when trying to load modules from a file:// url, without a server, but can happen with a mis-configured server.

It's likely that the file extension .mjs is unrecognized by the server so its unable to serve it with the right MIME type.

Balata answered 4/1, 2020 at 22:42 Comment(0)
Y
3

I had the same problem with a web server at my hoster. ".mjs" is apparently not yet supported by many web servers. See also: https://github.com/GeoffreyBooth/js-mjs-mime-type-test

So, if the server does not respond with correct MIME-Type for .mjs or other files, you may be able to add this Type in the .htaccess with

<IfModule mod_mime.c>
  AddType text/javascript mjs
</IfModule>

That solved the problem for me.

Yip answered 3/3, 2021 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.