Function error not set when working with Ecmascript modules in the browser

Asked

Viewed 20 times

1

I am trying to work with modules in Javascript and came across a problem when calling a function that is in the file main.js for index.html.

<!doctype html>
<html lang="en">
<head>
    <title>ES modules</title>
    <script type="module" src="./main.js"></script>
</head>
<body>

    <script>
        fnFuncionou()
    </script>

</body>
</html>

That one main.js imports a text variable from another file, the mods.js.

import texto from './mod.js'
console.log(`Fora da função ${texto}`)

function fnFuncionou() {
    console.log(`Dentro da função ${texto}`)
}

Below the code of mods.js:

let texto = "funcionou!"

export default texto

When executing the index.html, I get the message from console.log(Outside of function ${text}), which is out of function in the main.js. However, the function fnFuncionou() is not called, giving the following error message:

index.html:10 Uncaught ReferenceError: fnFuncionou is not defined

Could anyone tell me why this is happening? It is possible to call this function fnFuncionou() without changing the file structure of the folder? I summarized the problem, because the files I am working have much more code.

1 answer

2


When you add the attribute type="module" in a script, it is no longer treated in the conventional way. Therefore, the functions (globally) stated in it are not accessible to HTML.

That’s why you can’t call fnFuncionou in your HTML, assuming it is part of the global scope. That’s not what happens.

When working with modules, you must be explicit. Therefore, you must import fnFuncionou. Thus:

Filing cabinet main.js:

import texto from './mod.js';

console.log(`Fora da função ${texto}`);

// Note que a função está sendo exportada:
export default function fnFuncionou() {
  console.log(`Dentro da função ${texto}`);
}

Filing cabinet index.html:

<!doctype html>
<html lang="en">
<head>
  <title>ES modules</title>
</head>
<body>
  <script type="module">
    import fnFuncionou from './main.js';

    fnFuncionou();
  </script>
</body>
</html>

Note that I used the attribute type="module" in the <script> of index.html. Otherwise, I could not use the import statement.

The way out will be something like:

Fora da função funcionou!
Dentro da função funcionou!
  • Thank you very much!

Browser other questions tagged

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