简体   繁体   中英

Can I use imported functions and classes globally in JavaScript?

I want to switch from all classes in the html header file to the module approach.

I want to use some methods and function on buttons and other elements.

In my index.html in the head section:

<script src="js/main.js" type="module" defer></script>

Inside the main.js:

import {writeAlert} from './test.js';

Inside the test.js:

export function writeAlert () {
    alert('I am an alert');
}

Inside the body element of the index.html

<button onlick="writeAlert()">Alert</button>

I am getting the error message that the function (or in other cases class) is not defined. So what is the way to implement a global use of imported functions? Is the client actually able to see my whole source code with that approach?

Identifiers imported in a module are not visible on the outside.

Two solutions, in order of personal preference:

  1. Move the callback installation from HTML to JS:
    • Change the button definition to: <button id="alertButton">Alert</button>
    • Add the following code to main.js , or another module that imports writeAlert :
     document.addEventListener("DOMContentLoaded", () => { document.getElementById("alertButton").onclick = writeAlert; }); 
  2. "Export" writeAlert onto window in one of the modules:
     import { writeAlert } from "./test.js"; window.writeAlert = writeAlert; 
    In this way, writeAlert is accessible anywhere in your code, HTML or JS, without any imports. But this rather defeats the purpose of using imports in the first place and isn't as elegant.

This is a patchy answer. But, the same idea can be extended further.

In main.js:

import {writeAlert} from './test.js';
window.writeAlert = writeAlert;

After that, “writeAlert” is accessible from HTML file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM