简体   繁体   English

如何在浏览器中使用已编译的ES6到ES5文件?

[英]How to use a compiled ES6 to ES5 file in browser?

I have two modules in ES6: 我在ES6中有两个模块:

//mycalss.js
class MyClass {
}
export {MyClass};

//main.js
import {MyClass} from './../src/myclass';

And I am using Laravel-mix to handle the compilation and bundle process. 我正在使用Laravel-mix来处理编译和捆绑过程。

In the end I end up with a main.js . 最后,我得到一个main.js

I link this file in my html. 我将此文件链接到html中。

<script type="text/javascript" src="main.js"></script>

And try to make a reference to the class MyClass : 并尝试引用类MyClass

<script type="text/javascript">

    var object = new MyClass();

</script>

But a Uncaught ReferenceError: MyClass is not defined is thrown. 但是引发了Uncaught ReferenceError: MyClass is not defined

So, how do I use a classe compiled from es6 to es5 in my html? 因此,如何在html中使用从es6编译为es5的类?

ES6 modules have module scope. ES6模块具有模块范围。 This prevents them from leaking variables to global scope. 这样可以防止它们将变量泄漏到全局范围。 This is exactly what modularity is for. 这正是模块化的目的。

In order to use items from ES6 modules (the same applies to CommonJS modules or IIFEs that implement module pattern) in global scope, they have to be defined as globals. 为了在全局范围内使用ES6模块中的项(同样适用于实现模块模式的CommonJS模块或IIFE),必须将它们定义为全局项。 In the case of client-side script this means that they should be defined as window properties inside bundled application: 对于客户端脚本,这意味着应将它们定义为捆绑的应用程序内的window属性:

window.MyClass = MyClass;

This indicates potential XY problem. 这表明潜在的XY问题。 A better option is to reconsider the reasons why it should be available in global scope. 更好的选择是重新考虑为什么应在全球范围内使用它的原因。 If there is bundled ES6 application already, it is supposed to run code from inline <script type="text/javascript">...</script> too. 如果已经捆绑了ES6应用程序,那么它也应该从内联<script type="text/javascript">...</script>运行代码。

You can use Babel to compile JavaScript from ES6 to ES5 in browser. 您可以使用Babel在浏览器中将JavaScript从ES6编译为ES5。

Often, you have to use webpack to do that automatically for you and insert the script inside HTML. 通常,您必须使用webpack为您自动执行此操作,然后将脚本插入HTML。

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

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