JavaScript Module Export & Import in browser... How can I do this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

JavaScript Module Export & Import in browser... How can I do this?

I coded like following. -- file.js -- export function msg(m) { alert(m); } -- main.html -- <!DOCTYPE html> <html> <body> <script type="module"> import {msg} from "file.js"; // I also tried with "./file.js", "/file.js" and "file" but failed. msg("Hi!"); </script> </body> </html> and I saved these files in same path(file:///sdcard/) I expected main.html will pop alert with text "Hi!" but when I open main.html in chrome it didn't do anything. What's wrong with this script?

16th May 2017, 9:03 AM
김정제(Legacy)
김정제(Legacy) - avatar
5 Answers
+ 9
@Calvin Yes, right. In fact, I added Babel in that html file's<head> part like this <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> but Question description's max-length is 512 so I erase it.
16th May 2017, 9:14 AM
김정제(Legacy)
김정제(Legacy) - avatar
+ 6
@Calvin babel doesn't bundle module , it transpile one JS version to another. use webpack for module bundling
16th May 2017, 9:51 AM
Apel Mahmod
Apel Mahmod - avatar
+ 5
@Calvin as far as i know babel doesn't handle module loading you have to use other tools for module loading. please read the bottom part of doc . i would love if you prove me wrong since i will learn something new ♥
16th May 2017, 10:52 AM
Apel Mahmod
Apel Mahmod - avatar
+ 2
Javascript export/import is not implemented in most browsers yet. You could use Babel to transpile.
16th May 2017, 9:10 AM
Calviղ
Calviղ - avatar
+ 2
@Mohd Babel should transpile import export to js according to their doc. https://babeljs.io/learn-es2015/ (refer module section)
16th May 2017, 10:27 AM
Calviղ
Calviղ - avatar