How to access variables across Javascript files with babel?

放肆的年华 提交于 2019-12-14 01:01:53

问题


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 }
})();

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>

to this:

<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>

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?


回答1:


Please actually read the documentation for babel-browser

Not intended for serious use
Compiling in the browser has a fairly limited use case, so if you are working on a production site you should be precompiling your scripts server-side. See setup build systems for more information.

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';



回答2:


ES6 exporting only takes the exported parts and everything else is practically equivalent of being in a function, to import appleModule

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

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

import  {appleModule as appleModule}  from './apple';


来源:https://stackoverflow.com/questions/33314611/how-to-access-variables-across-javascript-files-with-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!