ES6 module support in Chrome 62/Chrome Canary 64, does not work locally, CORS error

mark pavlis picture mark pavlis · Oct 28, 2017 · Viewed 24.9k times · Source

Index.html

<html>
    <head>
    <script type="module">
        import {answer} from './code.js'
        console.info("It's ${answer()} time!")
    </script>
    </head>
    <body>
    </body>
</html>

code.js

export function answer(){
    return 'module';
}

Error: Access to Script at 'file:///C:*******/es6/code.js' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.

Chrome says it can support modules and I have seen examples working on the web, but when I copy them of download and run them locally, I always get the error above. I do not want to use Babel, Webpack, etc.

I have tried enabling the Experimental Web Platform features flag in both Chrome and Chrome Canary.

Answer

Alexander O&#39;Mara picture Alexander O'Mara · Oct 28, 2017

Unlike regular scripts, ES6 modules are subject to same-origin policy. This means that you cannot import them from the file system or cross-origin without a CORS header (which cannot be set for local files).

Basically you need to run this code from a (local) server or disable same-origin in the browser for testing (do not do this permanently). See: Access to Image from origin 'null' has been blocked by CORS policy.