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?
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.