meteor简介
What
“Meteor gives you a radically simpler way to build realtime mobile and web apps, entirely in JavaScript from one code base.”
简单来讲,Meteor基于Node来开发实时应用,复用前后端JS代码。
Why
-
从 client 到 server, 从 package 到 数据库 api,全部都是JS
-
跨端
-
实时渲染
安装
OS X or Linux 平台
curl https://install.meteor.com/ | sh
Windows 平台需要下载 exe 文件安装。
使用
使用 meteor create
新建项目,进入项目目录, 执行 meteor
命令,运行,即可在浏览器查看。
应用文件结构
-
/server 文件夹中的代码只会在服务器端运行。
-
在 /client 文件夹中的代码只会在客户端运行。
-
其它代码则将同时运行于服务器端和客户端上。
-
请将所有的静态文件(字体,图片等)放置在 /public 文件夹中。
模版
client 目录下的 main.html 是主入口,页面的模版文件放在 templates 目录下,模板的引用语法`` 表示引用 templates 目录下模版名为 ‘postList’ 的模版(这个和文件名没有关系),模版语法
<template name="postsList">
<div class="posts">
</div>
</template>
client 中文件的修改会触发网页reload刷新,类似livereload机制。
数据库
启动应用是,会启动3个服务:proxy, mongoDB, http server.
这里已经启动了一个mongod的服务,可以执行 meteor mongo
进入mongo shell,然后敲各种熟悉的命令进行db操作。
对db操作的REST接口,server 和 client 都可以用到,可以直接放到collections目录下。
Posts = new Mongo.Collection('posts');
注意: 这里没有用var定义,所有Posts是一个全局变量,server 要使用Posts对象时,并不需要应用相应的文件,直接引用即可
if (Posts.find().count() === 0) {
Posts.insert({
title: 'Introducing Telescope',
url: 'http://sachagreif.com/introducing-telescope/'
});
}
客户端获取db的数据,也直接调用Posts的方法
Posts.find();
赠品
-
包管理,类似于npm机制,安装某个meteor包,只需要
meteor add xxx
-
终端调试,可以用meteor指令将app安装到模拟器中运行
-
与angular和react无缝对接
终有一天,前端将抛弃CGI、后台,开发出一款属于自己的APP。