繁体   English   中英

在Meteor中使用ES6导入还为时过早吗?

[英]Is it too early to use ES6 import and export in Meteor?

因此,我一直在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 Dev Tools时, 确实显示了animal.speak()console.log(globalCode.add(5,6))的输出,但是当我手动键入let animal = new Animal('cat')globalCode.add(5,6)到控制台我得到Animal not definedglobalCode没有定义,分别。

显然,目前还没有浏览器正式支持ES6模块,但是我对为什么console.log(globalCode.add(5,6))let animal = new Animal('cat');感到困惑let animal = new Animal('cat'); index.js运行时有效,但从浏览器运行时无效。

上述限制使调试非常困难。 暂时最好不要使用ES6模块吗? 并且在Meteor服务器端是否完全支持它们?

导入会创建词法绑定,尽管您有自己的名字,但它们不是全局的。 (实际上,模块中都不是var绑定。)如果要将它们安装在全局对象上,可以将window.globalCode = globalCode或类似内容放在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));

});

为了回答您有关es6的问题,我会尽可能使用它,并建议使用相同的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM