Import Not Working In Chrome
Solution 1:
Here is a working example
file1.mjs
functionlog1() {
console.log('log1');
}
functionlog2() {
console.log('log2');
}
export { log1, log2 };
file2.mjs you must explicitly write .mjs extension
import { log1, log2 } from'./file1.mjs';
log1();
log2();
index.html Notice attribute type="module"
<body><scripttype="module"src="file2.mjs"></script></body>Then you need a static server to get rid of CORS block.
$ yarn globaladd serve
$ serve ./
Finally go to http://localhost:5000 and it will work
Update: It is recommended to use .mjs file extension for modules instead of .js
Solution 2:
Chrome (v70) has some kind of issues when working with import syntax on the local files served using file protocol. It is probably CORS blocking that can happen using file 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 compose html with js modules using file:// 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 htmlscriptelement (<script type="module" src="file-A.js"></script>)
Post a Comment for "Import Not Working In Chrome"