1

I'm using Meteor and have created some classes on the server. How can I make them accessible when I want to declare them inside other files on the server?

For instance, I will be separating each class function into its own file as each one will be large. How can I initialise and use the class when I need it? E.g.

Importing a file could be done like this

var User = require('./userclass.js');
var user = new User();

server/lib/classfile.js

class User {

    constructor(params) {

        this._firstName = params.firstName;
        this._lastName = params.lastName;
        this._email = params.email;
    }
}

server/file.js

var myVar = new User(someParams)
// this is undefined
meteorBuzz
  • 3,110
  • 5
  • 33
  • 60
  • Is your class file actually names "classfile.js" or "userclass.js"? You problem may just be load order of the files, and not accessibility.... – Soren Oct 08 '15 at 13:33
  • that is just an example of doing this in node, however, I am unfamiliar in how to do this in meteor – meteorBuzz Oct 08 '15 at 13:40

1 Answers1

3

You cannot define dependencies in Meteor using require -- meteor is somewhat expected to figure that out for you, however it is far from perfect, and for bootstrap code you would need to pay attention to the load order of the files (The Meteor documentation have a section on load order, you should read that, but in short files in lib are loaded first and all files are loaded in alphabetical order..

That being said, with the class feature being new in ES2015 it looks like a bug that classes are not properly exported by Meteor, but you can do a workaround for that.

The following works for me using Meteor version 1.2.0.2 ...

lib/user.js

class xUser {
    constructor(params) {
        console.log(params)
    }
    toString(){return "Hi";}
}
User = xUser   // this is avaiable in global space

server/bootstrapcode.js

var myVar = new User("Hello")
console.log(myVar.toString());
Soren
  • 14,402
  • 4
  • 41
  • 67
  • Sorry, I should have been clearer, I'd like to initialise the class only when it is needed, and not having it available globally. – meteorBuzz Oct 08 '15 at 15:32
  • You could always create your own scope object (like what node.js `require` implements) and just export and import modules as needed -- however that is not a standard functionality of Meteor. – Soren Oct 08 '15 at 20:36
  • module is not defined if I try to export it. module.exports = User; – meteorBuzz Oct 09 '15 at 09:13
  • There is no `module` or `export` in meteor - meteor automatically exports what is written to global scope within the file -- that is why the last line of user.js is `User = xUser;` – Soren Oct 09 '15 at 15:32