简体   繁体   中英

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

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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