如何避免将JavaScript ES6模块导出添加到全局范围以用于普通脚本块? [英] How do I avoid adding JavaScript ES6 module exports to global scope for use in normal script blocks?

查看:22
本文介绍了如何避免将JavaScript ES6模块导出添加到全局范围以用于普通脚本块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经设法避免进行硬性JavaScript编程,但是看来这即将结束.在为一个新的大型项目做准备时,我正在努力使自己在2018年获得最佳实践.我一直在阅读许多关于不同模块方法的文章,并利用了一些类似Dojo基于AMD的模块的方法.在考虑如何设计自己的模块体系结构时,似乎ES6是进行新开发的正确方法.到目前为止,我已经了解了导入/导出语法,并获得了一些简单的模块来工作.但是我目前使用HTML加载模块并使用它们的技术感觉不对".让我把到目前为止的工作归纳一下.

I've so far managed to avoid hardcore JavaScript programming but it looks like that is coming to an end. In gearing up for a major new project, I'm trying to get my head around best practices in 2018. I've been reading a lot about different module approaches and have made use of some like Dojo's AMD-based modules. In thinking about how to design my own module architecture, it seems like ES6 is the right way to go for new development. So far I understand the import/export syntax and have gotten some simple modules to work. But my current technique for loading the modules back in HTML and using them just "feels wrong". Let me boil down what I have working so far.

模块foo.js

import (bar} from '/Scripts/bar.js'

export function foo() {
    bar();
    console.log("I'm in foo");
}

模块bar.js

export function bar() {
    console.log("I'm in bar");
}

index.html

index.html

<head>
    <script type="module">
        import {foo} from "/Scripts/foo.js"
        window.foo = foo;   // save for later but "feels wrong"
   </script>
</head>

<body>
    <script>
        // foo();      // doesn't work - foo by itself is only defined in the module scope
        window.foo();  // unless "stashed" somewhere else
    </script>
</body>

也许这是适当的技术(我发现一个与我基本相同的较旧的问题),但仍然不觉得我应该像这样污染全局名称空间.假设那很不好,我还应该做什么?

Maybe this is proper technique (and I found an older question that did basically the same as me), but it still doesn't feel like I should be polluting the global namespace like this. Assuming that's bad, what else should I be doing?

推荐答案

如果您希望该函数在全局范围内可用,则实现该功能的唯一方法是将其置于全局范围内(又称 window 目的).

If you want the function available globally, the only way to achieve that is to put it on the global scope (AKA the window object).

将事物放到全局范围的一种更好的方法是拥有某种包含所有全局变量的 globals 对象,而不是直接在函数/属性名称上放上 window 对象,可能会导致与其他第三方库发生冲突.

A little bit nicer way to put things on the global scope, however, is to have some sort of globals object that contains all of your globals, rather than putting the function/property names directly on the window object which can potentially cause conflicts with other third-party libraries.

所以您会说 globals.foo()而不是 window.foo()

这篇关于如何避免将JavaScript ES6模块导出添加到全局范围以用于普通脚本块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆