Reputation: 5254
So I've been doing some coding in ES6 and trying to figure out how the import/export stuff works.
/lib/globalcode.js
'use strict';
let globalCode = {
add: (x,y) => {
return add(x,y);
}
};
let add = (x,y) => {
return x + y;
};
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
};
export { Animal, globalCode };
/client/index.js
import { Animal, globalCode } from '/lib/globalcode.js';
Template.index.onRendered( () => {
let animal = new Animal('cat');
animal.speak();
console.log(globalCode.add(5,6));
});
When I go into Chrome Dev Tools the output from animal.speak()
and console.log(globalCode.add(5,6))
do show up, but when I manually type let animal = new Animal('cat')
and globalCode.add(5,6)
into the console I get Animal not defined
and globalCode
not defined, respectively.
Apparently no browsers officially support ES6 modules yet, but I'm confused on why console.log(globalCode.add(5,6))
and let animal = new Animal('cat');
work when run from index.js
but not when run from the browser.
The limitation above makes debugging very difficult. Is it best to stay away from ES6 modules for the time being? And are they fully supported on the Meteor server side?
Upvotes: 0
Views: 120
Reputation: 1245
Imports create lexical bindings, which are, despite your names, not global. (Actually, neither are var
bindings in modules.) If you want to install them on the global object, you can put window.globalCode = globalCode
or similar in index.js
.
Upvotes: 2
Reputation: 559
I think the problem is a variable scoping problem. If you were to import at the top of your 'client/index' page, I think you would get the desired result:
import { Animal, globalCode } from '/lib/globalcode.js';
Template.index.onRendered( () => {
let animal = new Animal('cat');
animal.speak();
console.log(globalCode.add(5,6));
});
And to answer your question about es6, I use it everywhere I can and would recommend the same.
Upvotes: 0