DEV Community

Pere Sola
Pere Sola

Posted on

3 1

Vanilla JS - how to work with modules

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay