所以我在ES6中做了一些编码,试图弄清楚导入/导出的工作原理。
/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));
});
当我进入Chrome开发者工具时,animal.speak()
和console.log(globalCode.add(5,6))
的输出会显示,但是当我手动输入let animal = new Animal('cat')
和{{1}时进入控制台后,我分别得到globalCode.add(5,6)
和Animal not defined
。
显然没有浏览器正式支持ES6模块,但我对从globalCode
运行时console.log(globalCode.add(5,6))
和let animal = new Animal('cat');
工作的原因感到困惑,但是从浏览器运行时却没有。
上述限制使调试变得非常困难。暂时远离ES6模块是最好的吗?它们是否完全支持Meteor服务器端?
答案 0 :(得分:2)
Imports创建词法绑定,尽管你的名字是不全局。 (实际上,模块中的var
绑定都不是。)如果要在全局对象上安装它们,可以在window.globalCode = globalCode
中放置index.js
或类似内容。
答案 1 :(得分:0)
我认为问题是变量范围问题。如果您要在“客户/索引”的顶部导入。页面,我想你会得到理想的结果:
import { Animal, globalCode } from '/lib/globalcode.js';
Template.index.onRendered( () => {
let animal = new Animal('cat');
animal.speak();
console.log(globalCode.add(5,6));
});
为了回答你关于es6的问题,我尽可能地使用它并且会推荐它。