[英]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. 我想从html标头文件中的所有类切换到模块方法。
I want to use some methods and function on buttons and other elements. 我想在按钮和其他元素上使用一些方法和功能。
In my index.html in the head section: 在我的index.html的头部部分:
<script src="js/main.js" type="module" defer></script>
Inside the main.js: 在main.js中:
import {writeAlert} from './test.js';
Inside the test.js: 在test.js中:
export function writeAlert () {
alert('I am an alert');
}
Inside the body element of the index.html 在index.html的body元素内部
<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: 两种解决方案,按个人喜好顺序排列:
<button id="alertButton">Alert</button>
<button id="alertButton">Alert</button>
main.js
, or another module that imports writeAlert
: main.js
或另一个导入writeAlert
模块中: document.addEventListener("DOMContentLoaded", () => { document.getElementById("alertButton").onclick = writeAlert; });
writeAlert
onto window
in one of the modules: writeAlert
到模块之一中的window
上: import { writeAlert } from "./test.js"; window.writeAlert = writeAlert;
In this way, writeAlert
is accessible anywhere in your code, HTML or JS, without any imports. writeAlert
。 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: 在main.js中:
import {writeAlert} from './test.js';
window.writeAlert = writeAlert;
After that, “writeAlert” is accessible from HTML file. 之后,可以从HTML文件访问“ writeAlert”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.