简体   繁体   English

浏览器中的 JavaScript 模块有什么意义?

[英]What is the point of JavaScript modules in browsers?

So I'm taking on coding project at the moment, and while I was digging around looking for a solution to tackle a particular problem, I came across 'modules'.所以我目前正在从事编码项目,当我四处寻找解决特定问题的解决方案时,我遇到了“模块”。 While I've heard the term before, I decided that it would be worth looking into what modules actually were and how they were used.虽然我之前听说过这个术语,但我认为有必要研究一下模块实际上是什么以及它们是如何使用的。

From what I gathered, a module is a 'bit of code'.从我收集到的信息来看,一个模块就是一段“代码”。 Be it, functions, variables, classes, that are present in one JavaScript file, that can be exported / imported, to / from another JavaScript file.无论是函数、变量、类,都存在于一个 JavaScript 文件中,可以从另一个 JavaScript 文件导出/导入。

This seemed to be a bit pointless - why go to the trouble of exporting a script / set of scripts if I can use them from another file anyway?这似乎有点毫无意义 - 如果我可以从另一个文件中使用它们,为什么 go 还要麻烦导出脚本/脚本集?

Here's an example of what I'm on about:这是我正在谈论的一个例子:

// File 1 - adding.js

var c;

function add(a, b) {
    c = a + b;
    return c;
}
// File 2 - main.js

var d;
d = add(6, 4);

As far as I know, that would work, main.js would be able to access scripts in adding.js , without needing to export the add() function.据我所知,这会起作用, main.js将能够访问adding.js中的脚本,而无需导出add() function。

Maybe its different when using non-browser JavaScript, or perhaps I've misunderstood what modules are, but if this is the case, why use modules at all?使用非浏览器 JavaScript 时可能会有所不同,或者我可能误解了模块是什么,但如果是这种情况,为什么还要使用模块呢?

yes, you are right, you don't need to export add function but you should be careful with the order of importing files.是的,你是对的,你不需要export add function 但你应该注意导入文件的顺序。 Meaning that you should import adding.js before importing main.js .这意味着您应该在导入adding.js之前导入main.js

<html>
    <head>
        ...
    </head>

    <body>
        ...
        <script src="adding.js">
        </script>
        <script src="main.js">
        </script>
    </body>
    
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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