max pleaner
max pleaner

Reputation: 26788

How to structure Meteor app and load into Meteor shell

I'm having a number of issues putting together a very simple piece of code as I learn Meteor. See the comments, which are questions.

server/main.js

import { Meteor } from 'meteor/meteor';

import { Post } from './schema'
// Why is this required to make Post available in Meteor.startup?
// Isn't there auto-loading?

Meteor.startup(() => {
    console.log(Post)
    // This works, but why isn't Post available to meteor shell?
});

server/schema.js

import { Post } from './models/post'
export { Post }

server/models/post.js

import { Class } from 'meteor/jagi:astronomy';
// Why can't this be imported elsewhere, like main.js?

const Posts = new Mongo.Collection('posts');
const Post = Class.create({
  name: 'Post',
  collection: Posts,
  fields: {
    title: { type: String },
    userId: String,
    publishedAt: Date
  },
});

export { Post }

In addition to these questions, how can I load my app into meteor shell? Post is undefined there, even though it's defined in Meteor.startup. I tried using .load with an absolute path, but this breaks my app's imports, which use relative paths.

As for which errors I'm confused about:

Upvotes: 0

Views: 142

Answers (1)

aedm
aedm

Reputation: 6624

To access exported objects in Meteor shell, use require:

> require('server/schema.js').Posts.findOne();

To access objects exported by packages, use the package name:

> require('react').PropTypes;

The reason you can't access an object that's imported by another js file is that each file has its own scope here. When Meteor builds your app, it doesn't just concatenate js files like many other build systems do, and that's really a good thing.

Basically a Javascript object gets created for every js file you write. Anything you export in a js file becomes a field in this object which you can access by using require. And import is just a nicer version of the same thing.

Upvotes: 2

Related Questions