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=".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?
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./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?
2 Answers
Reset to default 4Please 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 prepiling 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';
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';