DEV Community

Pere Sola
Pere Sola

Posted on


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">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <button id="but">Click me</button>
    <div id="container"></div>
    <script src="script.js"></script>
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.

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git