【问题标题】:How to structure Meteor app and load into Meteor shell如何构建 Meteor 应用程序并加载到 Meteor shell
【发布时间】:2016-06-11 21:52:17
【问题描述】:

在学习 Meteor 时,我在编写一段非常简单的代码时遇到了很多问题。请参阅 cmets,它们是问题。

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 }

除了这些问题,我怎样才能将我的应用程序加载到流星外壳中? Post 在此处未定义,即使它已在 Meteor.startup 中定义。我尝试将.load 与绝对路径一起使用,但这会破坏我的应用程序的导入,它使用相对路径。

至于我对哪些错误感到困惑:

  • 当我尝试在Meteor.startup() 中使用import 时,我收到一个错误,指出关键字import 未定义。我正在使用ecmascript 包。
  • 当我在使用Class 的同一文件中没有import { Class } 时,我会收到未知关键字错误。
  • 如果我在 main.js 中没有 import { Post },那么 Post 是未定义的。
  • 无法将应用程序加载到 Meteor shell。

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    要在 Meteor shell 中访问导出的对象,请使用require

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

    要访问包导出的对象,请使用包名:

    > require('react').PropTypes;
    

    你不能访问由另一个 js 文件导入的对象的原因是每个文件在这里都有自己的范围。当 Meteor 构建您的应用程序时,它不只是像许多其他构建系统那样连接 js 文件,这真的是一件好事。

    基本上,您编写的每个 js 文件都会创建一个 Javascript 对象。您在 js 文件中导出的任何内容都将成为此对象中的一个字段,您可以使用 require 访问该字段。而import 只是同一件事的一个更好的版本。

    【讨论】:

    • 谢谢。除非我想将我的依赖项作为参数传递给函数,否则我应该在多个文件中包含相同的依赖项吗?有没有办法共享从“包含”到“包含”的范围?
    • 是的,每个js文件都应该独立导入所有的依赖。默认情况下,您不能继承依赖项。 (好吧,我相信有很多方法可以解决这个问题,因为它是 Javascript。)
    • 还有自动加载吗?
    • 是的。事实上,Meteor 的生产构建为您的应用创建了一个单一的整体 js 文件,其中包含每个源文件和包。
    • 好的,但是为什么我必须在我的 main.js 文件中 import { Post } from './schema' 呢?
    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2014-03-30
    • 2021-08-02
    • 2013-04-04
    • 1970-01-01
    • 2018-02-11
    • 2016-01-21
    相关资源
    最近更新 更多