I am creating an single page app in vanilla JavaScript. I want to organize my code in different files to make it modular, which means I should be able to access functions defined in one file in another file. I am using ES6 native import
export
for this:
file-1.js:
export function func1() {}
export function func2() {}
file-2.js:
import { func1, func2 } from './file-1';
index.html:
<script src="file-1.js"></script>
When I run index.html in Chrome (version 65), I get the following error:
Uncaught SyntaxError: Unexpected token {
.
What's wrong in my code? Chrome 65 fully supports ES6 module system.
Chrome (v70) has some kind of issues when working with
import
syntax on the local files served usingfile
protocol. It is probably CORS blocking that can happen usingfile
protocol according to some articles. But Chrome also does not show CORS warning in the console in this case - which is strange. Therefore some kind of HTTP server is needed so the files are served via HTTP protocol (as Vu showed in his answer). Firefox v63 (probably >v60) doesn't have these issues and you can composehtml
withjs
modules usingfile://
protocol without a special server.Also make sure to:
use file type extensions when importing (
import { func1, func2 } from './file-B.js';
).use
type="module"
in htmlscript
element (<script type="module" src="file-A.js"></script>
)Here is a working example
file1.mjs
file2.mjs you must explicitly write
.mjs
extensionindex.html Notice attribute type="module"
Then you need a static server to get rid of CORS block.
Finally go to
http://localhost:5000
and it will workUpdate: It is recommended to use
.mjs
file extension for modules instead of.js