前端快速开发模版

原文地址:前端快速开发模版

之前一直在开发移动端的单页面应用,而移动web对性能和效果要求是比较苛刻的,所以用的都是轻量级的框架体系。基本上是Zepto加自己开发的单页面框架,再加上若干简单的库。这样前端要加载的文件很小,修改起来也非常方便,同时这样的轻量级的体系使用gulp进行自动化管理也是非常合适的。

自从开发react项目后,对它的工程化和开发模式也是开了眼界,标准的框架体系就是重量级的react+redux+webpack。开发大型项目和后台管理系统用react,vue确实是不错的。但是开发一些小项目,比如前端h5之类的又有杀鸡用牛刀的感觉。

于是借鉴webpack工程化思想动手写了个前端快速开发模版,用于开发快速简洁的项目,比如之前的单页面应用。而这个项目模版就是类似前端开发的脚手架了,基本的思路就是自动化和前端编译,主要达到以下目的:

  1. 使用less预编译css,使用autoprefixer进行样式兼容
  2. js代码用babel编译,因此可基于es6,es7编写代码
  3. 类库文件使用npm包,js文件使用browserify组织和打包,不再使用sea,require之类的加载器
  4. html代码使用swig模版引擎进行组织和预编译
  5. 静态资源版本使用rev管理,当css或js文件内容有变化,打包时自动更新版本
  6. 前端开发基础样式,框架的整合。

工具链

  • 构建工具gulp
  • 编译打包工具browserify
  • 代码编译babel
  • css兼容autoprefixer
  • css预编译less
  • html代码预编译模版swig
  • 前端代码版本更新rev

公共类库

  • jQuery
  • Zepto
  • 自己开发的简洁单页面框架app.js
  • 图标fontello
  • 字体reboto
  • 基础样式base.css

文件目录结构

  • css: css文件
  • less: less文件
  • js: js文件
  • dist: 打包生成的项目文件
  • layout: html母板
  • lib: 公共类库
  • template: html页面

项目自动化

没有使用重量级的webpack,而是使用轻量级的gulp和browserify

公共类库

公共类库的文件,主要有基础样式base.css,图标样式reboto,字体样式fontello,单页面框架app,直接拷贝到dist文件就ok。其他npm包跟nodejs项目一样在node_modules中,不需要处理。

//复制公共库目录下的所有内容
gulp.task('copy',function(){
  return gulp.src('./lib/**')
    .pipe(gulp.dest('./dist/lib/'));
});

css文件

首先将less文件转为css,用autoprefixer添加兼容性前缀,合并压缩,放到dist目录,最后用rev插件生成版本信息,这个后面用于替换更新链接用。

//编译css,添加兼容后缀,压缩
gulp.task('css', function() {
  return gulp.src('./less/*.less')
    .pipe(less())
  // .pipe(concatCss("index.css"))
    .pipe(postcss([ autoprefixer({
      "browsers": ["last 2 version", "> 0.5%", "ie 6-8","Firefox < 20"]
      // "browsers": ["last 2 version", "> 0.1%"]
    })
                  ]))
    .pipe(cleanCSS())
  // .pipe(rename({suffix: '.min'}))
  // .pipe(gulp.dest('./dist/css'));
    .pipe(rev())
    .pipe(gulp.dest('./dist/css'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('./rev/css'));

});

js文件

我这里有两个入口文件,可以随时将新入口文件添加到scripts数组中,这里做的就是使用babel转换代码,然后将外部文件,npm包打包进来,生成sourcemap,输出到dist文件夹,最后一样用rev插件生成版本信息。

var scripts=['app','index'];
scripts.map(name=>{
  gulp.task(name,function(){
    return  browserify({
      entries:'./js/'+name+'.js',  //entries file name
      debug:true // set true so the bundle file can generate sourcemap 
    })
      .transform(babelify,{ 
      plugins: ["transform-runtime"],
      presets: [
        'es2015',  //convert to es5
        'stage-0'  //es7
      ]
    })
      .bundle()  //merge
      .pipe(source(name+'.js'))
      .pipe(buffer())
    // .pipe(uglify())
      .pipe(sourcemaps.init({loadMaps: true})) //External sourcemap file
      .pipe(sourcemaps.write('./'))
      .pipe(rev())
      .pipe(gulp.dest('./dist/js/'))
      .pipe(rev.manifest(name+'.json'))
      .pipe(gulp.dest('./rev/js/'));
  });
});

html文件

html编译我使用的是模版引擎是swig,这里用的是gulp-swig插件,当然也可以用ejs或jade的引擎。但我个人比较习惯用swig,因为它更灵活,支持各种文件格式,可以直接使用html文件,也支持ejs不支持的layout等。gulp-swig插件的使用也非常简单。

//swig编译输出html
gulp.task('html', function() {
  return gulp.src('./template/*.html')
    .pipe(swig({
    defaults: {cache: false }
  }))
    .pipe(gulp.dest('./'))
});

文件版本控制

之前编译css和js的时候已经调用rev生成了记录了版本信息的json文件,如果内容有变化它会生成新的md5文件名。这里就是用rev-collector替换html文件中除md5部分外相同文件名的链接,这样就就实现了版本更新功能,用这个插件可以更新css,js,图片等的版本。

//更新css和js版本,同时替换html中的链接标签
gulp.task('rev', scripts.concat(["css","html"]),function () {
  return gulp.src(['./rev/**/*.json', './*.html'])//add md5 suffix to js and css file, replace the link of html as well 
    .pipe( revCollector({
    replaceReved: true,
    dirReplacements: {
      '/css': '/css',
      '/js': '/js'
    }
  }))
    .pipe( gulp.dest('./dist') );
});

html里面替换后的链接格式如下

<link rel="stylesheet" href="./css/app-d333f590b0.css">
<script src="./js/app-62bad8e549.js"></script>

项目模版

项目自动化配置完后,接着就是配置项目模版了,这里分两种类型的模版:1.移动端优先的单页面;2.pc端优先的普通页面。
swig标签语法

  • extends 继承父模板,必须在文件最前
  • block 定义一个块,使之可以被继承的模板重写,或者重写父模板的同名块
  • parent 将父模板中同名块注入当前块中
  • include 包含一个模板到当前位置

移动端单页面模版

在layout文件夹新建移动端的单页面模版app-layout.html,然后再建立子目录partial,用于存放公共代码块。

我们知道加载页面时再去加载外部文件是需要耗费加载时间,而页面直出可以大大提高加载速度,同时预先加载部分样式也可以避免加载时的白屏问题。这也是我们这里将公共部分的js和css以代码块的形式嵌入到html文件中,达到页面直出的效果。

swig支持将html文件嵌入,同时也可以将css文件嵌入,我这里就是把单页面样式文件app.css和基础样式文件app-base.css的内容直接输出到style标签中。主要的代码块有:

  • meta.html: 头部meta标签
  • header-script.html: 主要是动态设置fontsize大小的脚本
  • footer-script.html: 主要是页面加载过程的动画脚本

当然了图标样式,好看的字体文件,单页面的css,基础的样式css都有, 同时母版还挖出了几个block给继承的页面进行重写,比如block title,block css,block js,内容block content。css块和js块既可以写外部链接也可以直接写代码。 我们可以根据自己的需求进行修改和配置文件,具体内容看如下代码。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>{% block title %}{% endblock %}</title>
    {% include './partial/meta.html' %}
    <!-- 页面内加载的头部js -->
    {% include './partial/header-script.html' %}
    <!-- 页面内加载的css -->
    <style>{% include '../lib/app/app.css' %}{% include '../lib/app-base.css' %}</style>
    <!-- 图标 -->
    <link rel="stylesheet" href="./lib/fontello/fontello.css">
    <!-- 字体 -->
    <link rel="stylesheet" href="./lib/reboto/roboto.css">
    <!-- 项目css -->
    <link rel="stylesheet" href="./css/app.css">
    <!-- 外部css块 -->
    {% block css %}{% endblock %}
  </head>
  <body>
    <div id="app" class="view-wrap"></div>
    <div id="loading" class="loading-wrap">
      <div class="loading">
        <div class="round"></div>
        <div class="txt">0%</div>
      </div>
    </div>
    <div id="freshing" class="fresh-wrap">
      <div class="loading">
        <div class="round"></div>
        <p class="txt">loading...</p>
      </div>
    </div>
    <!-- 内容填充块 -->
    {% autoescape false %}
    {% block content %}{% endblock %}
    {% endautoescape %}
    <!-- 页面内加载的尾部js -->
    {% include './partial/footer-script.html' %}
    <!-- 外部js块 -->
    {% block js %}{% endblock %}
  </body>
</html>

PC端优先模版

接着就是建立PC端优先的模版layout.html,这个和单页面模版相似,主要区别就是基础样式,同时不用嵌入移动端的代码,页面模版请看如下代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>{% block title %}{% endblock %}</title>
    {% include './partial/meta.html' %}
    <link rel="stylesheet" href="./lib/fontello/fontello.css">
    <link rel="stylesheet" href="./lib/reboto/roboto.css">
    <style>{% include '../lib/base.css' %}</style>
    <link rel="stylesheet" href="./css/index.css">
    {% block css %}{% endblock %}
  </head>
  <body>
    {% autoescape false %}
    {% block content %}{% endblock %}
    {% endautoescape %}
    {% include './partial/copyright.html' %}
    {% block js %}{% endblock %}
  </body>
</html>

使用方式

项目模板完成了,我以建立单页面项目为例演示使用的步骤

  1. 首先从github clone模版到文件夹webapp-project,安装相关npm包。

    git clone https://github.com/edwardzhong/project-template.git webapp-project
    npm install
    
  2. 在less文件夹内建立app.less,并编写代码

    @lightBlue:hsl(198, 73%, 53%);
    
    // base
    html,body{
      font-family: "Roboto", "Helvetica Neue", Helvetica, "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
      font-size: 0.25rem;
      color: #555;
      width: 100%;
      height: 100%;
    }
    body,p,h1,h2,h3,h4,h5,h6{margin:0;}
    ul,ol{list-type:none; margin:0; padding:0;}
    // todo more ...
    
  3. 在js文件夹建立app.js并编写代码, 使用es6写代码就是舒服😊

    require('../lib/zepto.js');// zepto没有使用CommonJs规范,修改后使用require引入 
    import { webApp } from '../lib/app/app.js'
    
    var App=webApp({
      container:'app',
      animate:{ effects:['slideInRight', 'slideOutLeft'],delay:600},
      preLoad:function(){
    
      },
      aftLoad:function(){
        loadPercent(100);
      }
    })
    .other('/index',{temId:'tempIndex',create:createIndex})
    .when('/button',{temId:'tempButton'})
    .when('/form',{temId:'tempForm'})
    .when('/dialog',{temId:'tempDialog',create:createDialog})
    .init();
    
    // todo: more ...
    
  4. 在template文件夹建立app.html,引用单页面模板app-layout.html,并编写内容,我这里把单页面的各个视图代码也以代码块的方式引入。

    {% extends '../layout/app-layout.html' %}
    {% block title %}Web App{% endblock %}
    {% block js %}
    <script src="./js/app.js"></script>
    {% endblock %}
    {% block content %}
    {% include './partial/index.html' %}
    {% include './partial/button.html' %}
    {% include './partial/dialog.html' %}
    {% include './partial/form.html' %}
    {% endblock %}
    
  5. 运行自动化命令,进行编译,合并,压缩,打包

    npm run build
    
  6. 最后项目文件都输出到dist文件夹,找到app.html运行即可。

最后

代码请看https://github.com/edwardzhong/project-template.git

posted @ 2017-11-28 10:03  Jeff.Zhong  阅读(13205)  评论(0编辑  收藏  举报