Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use es6 classes in different files by importing them in Meteor?

I have recently discovered Meteor and I am struggling with using ES6 classes and imports in a new Meteor project. What I want to do is to have a complex structure of classes, which methods get called from Meteor events/methods/helpers. I've added Babel.js to the project by writing a command $ meteor add grigio:babel and it works properly.

Example of what I am trying to achieve:

in server/models/article.js:

class Article {
  static all() {
    //returns all articles from db
  }
}

in server/methods/articles.js:

Meteor.methods({
  allArticles: {
    Article.all();
  }
})

Having just that raises ReferenceError: Article is not defined in a methods file, which is adequate. So I have got three options: write all classes in one file, append all classes to a global object or use a good module system like Browserify. Obviously, third option is better.

But how do I use that? Babel converts export, import into Browserify by default and Meteor raises a require is not defined error on page refresh. After googling the problem I didn't find a clear solution on how to add Browserify to Meteor. Should I add a npm packages support to Meteor, add a npm package of browserify and add it manually to Meteor on every page where I import/export anything? Or should I use a completely different approach? How is this task usually handled in Meteor? Thank you!

like image 942
cbrwizard Avatar asked Mar 31 '15 11:03

cbrwizard


1 Answers

I was reading about this earlier and found this issue on github that may help.

Essentially just assign the class to a variable that is exposed to both the client and server (lib/both/etc depends on your file structure). Like so:

Article = class Article {...}

Seems to be the best solution at the moment.

like image 80
Tom Bates Avatar answered Sep 23 '22 13:09

Tom Bates