Import and Export Javascript functions and classes

Asked

Viewed 434 times

0

When I try to import a console class from the browser, the following error appears:

Uncaught SyntaxError: Cannot use import statement outside a module

Filing cabinet models/Evento.js:

export class Evento {
    constructor(descricao, horaInicio, horaTermino){
        this.descricao = descricao;
        this.horaInicio = horaInicio;
        this.horaTermino = horaTermino;
    }
}

Filing cabinet view/eventos.js:

import {Evento} from '../model/Evento';
function criarObjetoEvento(){
    let id = localStorage.length + 1;
    const descricao = document.getElementById("descricao").value;
    const horaInicio = document.getElementById("horaInicio").value;
    const horaTermino = document.getElementById("horaTermino").value;
    const e = new Evento(descricao, horaInicio, horaTermino);
    console.log(e);
    criarEvento(e);
}

It is possible to realize import and export this way for files that will be run in the browser? Or is there another way to perform modulation?

  • In HTML, how do you import the module?

1 answer

1

To use the declarations import and export, it is necessary that you declare that your script is of type module. Example: html -->

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Teste</title>
</head>

<body>
  <script src="./script.js" type="module"></script>
  <script src="./api.js" type="module"></script>
</body>

</html>

In this example I created two JS files where the api.js exports a variable to the script.js.

There’s also this link from Developer Mozilla who speaks on this subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.