4
votes

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?

2
Configure the server to serve .mjs files with an appropriate javascript MIME type, or simply try using .js file extension.someOne

2 Answers

3
votes

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.

1
votes

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.