DEV Community

loading...

Vanilla JS - how to work with modules

Pere Sola
Account Manager @Stripe during the day. Full stack software developer after-hours. @LambdaSchool graduate
・1 min read

I am reading You Don't Know Javascript and I want to really take time to practise what I have not worked on before. I was reading about Modules and since I have never used them on a Vanilla JS project I wanted to see how it works (I always use it in React).

I was following the MDN guide so I created a script.js file and a module.jsfile. The HTML file had the usual <script src="script.js"></script> tag.

My HTML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="but">Click me</button>
    <div id="container"></div>
    <script src="script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

My script.js file:

import { text } from "./module.js";

const target = document.getElementById("but");
const container = document.getElementById("container");

target.addEventListener("click", () => {
  container.textContent = text;
});
Enter fullscreen mode Exit fullscreen mode

My module.js file:

const text = "Yay";

export { text };
Enter fullscreen mode Exit fullscreen mode

Well, I was getting an error: Uncaught SyntaxError: Cannot use import statement outside a module. WTH, I thought.

After a bit of research, I found the solution: you need to add type=module in the script tag:

<script type="module" src="script.js"></script>
Enter fullscreen mode Exit fullscreen mode

It is also explained here.

Discussion (0)