如何使用babel访问JavaScript文件中的变量? [英] How to access variables across Javascript files with babel?

查看:361
本文介绍了如何使用babel访问JavaScript文件中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的代码从 ES5 迁移到 ES6 并使用 babel 。我在我的代码中使用模块模式,这样如果我有一个模块,如 apple ,我会做这样的事情:

I'm trying to migrate my code from ES5 to ES6 and use babel. I use the module pattern quite a bit in my code, such that if I have a module like apple I'll do something like this:

var appleModule = (function() {
    var yummy = true;
    var eat = function() { }

    return { "eat": eat }
})();

,然后在另一个文件中访问 appleModule 。但是,从...移动一切:

and then access appleModule in a different file. However, when moving everything from this:

<script type="text/javascript" src="/scripts/apple.js"></script>
<script type="text/javascript" src="/scripts/banana.js"></script>

到:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser.js"></script>
<script type="text/babel" src="/scripts/apple.js"></script>
<script type="text/babel" src="/scripts/banana.js"></script>

我不能再访问不同的 appleModule 文件。我得到一个 ReferenceError ,说它不存在。访问变量的文件与babel和ES6?

I can no longer access appleModule in different files. I get a ReferenceError saying it doesn't exist. How do access variables across files with babel and ES6?

推荐答案

请实际阅读 babel-browser


不适用于严重使用

在浏览器中编译的用例相当有限,因此如果您在生产站点上工作,则应该预编译脚本服务器端。有关详细信息,请参见安装构建系统

您不应该在生产环境中使用这样的babel-browser。

You're not supposed to use babel-browser like that in a production environment. Not even in a development one, really.

相反,为您的代码设置一个正确的构建步骤,以便您的代码可以转移并捆绑。

Instead, setup a proper build step for your code to transpile and bundle your code.

你甚至不需要创建自己的这样的模块

You don't even have to create your own modules like that

a.js

var yummy = true;
var eat = function(){};

export var eat;

b.js

import {eat} from './a.js';

这篇关于如何使用babel访问JavaScript文件中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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