Using Modules in the Browser (without WebPack)
I've been stuck with this for a while and after playing around I found a solution. You don't need any libraries or webpack to do this and I'm not sure this works outside of chrome.
- You need to run this code on a webserver or else it won't work (in other words, it has to be on localhost, NOT file://)
- Make a folder called
jsmodule
- create a file called
index.html
with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Js module</title>
</head>
<body>
<h1>JS module test</h1>
<script type="module" src="script.js"></script>
</body>
</html>
- Create a file in same folder called
script.js
with the following code:
import Person from './Person.js';
import Book from './Book.js';
let person1 = new Person();
let someBook = new Book();
- create a file in same folder called
Person.js
with the following code:
export default class Person{
constructor(){
alert("hallo from person");
}
}
- create a file in same folder called
Book.js
with the following code:
export default class Book{
constructor(){
alert("Hallo from book");
}
}
- Run the
index.html
on you webserver (localhost)