基于express的前端开发环境

Posted by Nutlee on 2016-08-28

express-gulp-browsersync

自动打包自动刷新 mock 环境,GitHub仓库

集成了 express ejs mock.js 等

使用环境

  1. 准备

    • 全局安装 gulp

      1
      npm install gulp -g
    • 下载所有文件

      1
      npm install
  2. 开发环境

    • 首次运行

      1
      gulp lib-init
    • 运行

      1
      gulp
  3. 生产环境

    • 直接强制打包

      1
      gulp fcompile
    • 打包并运行预览

      1
      gulp production
  4. 前端依赖

    初始化静态依赖 (已配置 bower.json 包含 jQuery 和 Bootstrap)

    1
    bower install

    在 gulpfile.js 中配置好需输出到 public 的前端依赖库核心文件,执行

    1
    gulp lib-init
  5. 文件说明

    src 文件夹下存放编译静态资源的源文件
    public 文件夹下放编译后的文件

    开发环境下只会进行 less 编译和从开发文件夹拷贝其他静态文件到发布为止(public)下。

    默认启动后打开

    1
    http://localhost:5000

    如果网页没反应请尝试手动刷新一次,或访问

    1
    http://localhost:5000/html/index.html

    如果接口占用,请在根目录下 gulpfile.js 文件中修改。

手动打包 src 文件夹下静态资源

  • less 编译、压缩 (搬运css、fonts)

    1
    gulp styles
  • js 压缩

    1
    gulp scripts
  • jshint 校验

    1
    gulp jshint
  • ejs 模板编译

    1
    gulp ejs
  • images 图片压缩

    1
    gulp images
  • 手动清空打包后的静态资源 慎用

    1
    gulp clean

    注:
    使用 命令后加 -dev 进行开发环境部署,如

    1
    2
    # 开发环境仅仅编译 less
    gulp styles-dev

手动启动服务器并开启浏览器自动刷新

1
gulp browser-sync

编写 mock 接口

在 router/index.js 中编写,或者在 router 文件夹内单独写 js 并且在 App.js 中引入。

使用 mock.js 产生随机数据,如

1
2
3
4
5
6
7
8
9
10
11
router.route('/test')
.get(function(req,res,next) {
var data = mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1
}]
});
res.send(data);
})

更多 mock.js 使用例子请查看官网

前端库安装

使用 bower 来管理前端库依赖,默认的依赖库下载到 bower_components 下。

  • 初始化 bower (当前项目已初始化)

    1
    bower init
  • 根据 bower.json 安装

    1
    bower install
  • 安装前端库并保存到 bower.json

    1
    2
    3
    4
    # jQuery 2.1.4
    bower install git@github.com:jquery/jquery.git#2.1.4 --save
    # Bootstrap 3.3.7
    bower install git@github.com:twbs/bootstrap.git#3.3.7 --save
  • 将库核心文件输出到 public 文件夹下,需在根目录下 gulpfile.js 中手动配置输出的内容

    1
    gulp lib-init
  • 卸载并从 bower.json 中删除

    1
    bower uninstall jquery --save
  • bower 配置 http/https 代理

    • 在用户更目录或者项目根目录下创建 .bowerrc 文件
    • 添加内容

      1
      2
      3
      4
      {
      "proxy": "http://127.0.0.1:8888",
      "https-proxy": "http://127.0.0.1:8888"
      }

ejs 模板

  • 头部复用

    html/common/head 中进行meta属性、css、公共js 加载和复用,最后形如下列代码的方式在也不同的页面使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <%- include('common/head',{
    title: 'ejs模板测试',
    styles:[
    '../lib/css/bootstrap.min.css',
    ],
    // 进行 cookie 检查
    cookie: {
    required: [],
    redirectTo: ''
    },
    }) %>
  • 尾部复用

    html/common/footer 中进行 js 的加载复用,使用形如以下形式的方式在不同页面使用

    1
    2
    3
    4
    5
    6
    <%- include('common/footer',{
    scripts: [
    '../lib/js/jquery.min.js',
    '../lib/js/bootstrap.min.js'
    ]
    }) %>