Search code examples
javascriptgoogle-chromeecmascript-6

ES6 modules in local files - The server responded with a non-JavaScript MIME type


I get this error:

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.

The project is run from local files, eg.: file:///D:/path/project.html.

Works without problems in Firefox, but doesn't work in Google Chrome. I want to test it this way for development purposes - it's more comfortable than creating a server and remembering what port is it on.


Solution

  • If you got onto this error message, it means that it's not a Same-origin issue.

    As said in the error message, the real problem is that modules scripts require the MIME of your script file to be one of the javascript MIME types.

    Your filesystem doesn't provide any MIME, hence the loading fails.

    So the best solution is obviously to run your code on a local server, and not on the filesystem.

    But since you do insist ;) One workaround is to first fetch your script file as Blob using XHR (fetch can't be used on file:// protocol), then force its type property to be one of js MIMEs, and set your <script>'s src to a blobURI poiting to this Blob.

    // requires to start chrome with the --allow-file-access-from-file flag
    var xhr = new XMLHttpRequest();
    xhr.onload = e => {
        let blob = xhr.response;
        blob.type = 'application/javascript'; // force the MIME
        moduleScript.src = URL.createObjectURL(blob);
    };
    xhr.open('get', "yourmodule.js");
    xhr.responseType = 'blob';
    xhr.send();
    

    BUT, you won't be able to import any dependencies from within your module.