构建更好的前端框架using gruntJS

Grunt is a task-based command line build tool for JavaScript projects。简单来说就是基于Grunt的前端的Build工具集合,包含各种功能。

也许你觉得它会是一个装Cool的工具,事实上我不想花时间去说明它是如何如何优秀。在这里发帖,只是想唤起大家的一种想法,JavaScript的开发不只是用一个Editor的年代了,国外的技术已经到了很成熟的地步了,跟或不跟,都在于你。我也是头一次接触到Grunt。

一、Grunt安装

Grunt的安装离不开NodeJS,所以,你首先要安装NodeJS,在Windows,Linux安装也是方便的,这里就是说了。安装完NodeJS之后,我们就可以安装Grunt了。

npm install grunt    //npm在后期已经集成在NodeJS

二、安装PhantomJS


这个东西是我用Grunt初始化一个Jquery 插件项目之后要我安装的,PhantomJS is a headless WebKit with JavaScript API. 大概是一个Webkit的东西,可以运行JavaScript的。当然功能是很强大的,用于截图,网页监测等。安装这个也很简单,我是在Windows下的,下载了一个zip然后解压,保证能在cmd下运行,所以要设置环境变量。

在cmd下,打phantomjs,能进入一个interactive mode (REPL)就可以了。

三、快速一个Jquery plugin环境

grunt init:jquery  //在window下,你要使用grunt.cmd,所以完整的是:grunt.cmd init:jquery

这里会用询问的方式来获取这个插件的信息,插件名字,版本号,作者,电子邮件等。所有东西都写好,它会问你要不要再修改,如果不用则打N。

这里是它的一个目录结构。

LICENSE-GPL
LICENSE-MIT
README.md
grunt.js
libs
|-- jquery
|    |-- jquery.js
|-- qunit
     |-- qunit.css
     |-- qunit.js
package.json
src
|-- jquery.demo.js   ---->这个将是以后完成插件的源码
test                         ---->测试版本
|-- jquery.demo.html
|-- jquery.demo_test.js

 四、检查刚才新建的项目

grunt.cmd  
D:\node>grunt.cmd
Running "lint:files" (lint) task
Lint free.

Running "qunit:files" (qunit) task
Testing my-first-jquery-plugin.html....OK
>> 4 assertions passed (59ms)

Running "concat:dist" (concat) task
File "dist/my-first-jquery-plugin.js" created.

Running "min:dist" (min) task
File "dist/my-first-jquery-plugin.min.js" created.
Uncompressed size: 536 bytes.
Compressed size: 263 bytes gzipped (372 bytes minified).

Done, without errors.

五、接下来要干什么

当然是核心的工作了,打代码。我前2天才开始看JQ插件制作,发现官网的说明文档风格不太适合我。下面是我看Twitter上的一些风格,比较适合我。

!(function($){

  "use strict";
  
  var somejQueryPlusin=function(element,options){
         
         this.$element = $(element);
         this.options = options;
         
  };
  
  somejQueryPlusin.prototype = {
        Constructor:"somejQueryPlusin",
        show:function(){
                alert('show');
        },
        hide:function(){
                alert('hide');
        },
         ..................
  };
  
  $.fn.somejQueryPlusin= function(options){
        return this.each(function(){    //JQ插件的核心
                var $this = $(this),
                options = $.extend({}, $.fn.somejQueryPlusin.defaults, typeof option == 'object' && option),
                data = $this.data('somejQueryPlusin');        
                
                if(!data) $this.data('somejQueryPlusin', (data = new somejQueryPlusin(this, options)));
                
        //        data['show']();
        });
  }
  
  $.fn.somejQueryPlusin.defaults = {
        //配置默认参数
  }
  


})(jQuery);

其实想更深入地介绍插件的开发,可惜功力不够。至今还没有发开过牛B的东西,慢慢来,楼主还是比较菜的。

最后,来说说大家的疑虑,为什么花这么长时间搞这些东西,最后才敲代码。这肯定是有原因的,这些工具的出现正是促进这个行业的,规范前端开发的全部东西。

如果我说不服你使用这些工具,不妨看看其他的是怎么用的?

利用-grunt-(几乎)无痛地做前端开发(一)
Meet Grunt: The Build Tool for JavaScript

原文地址:https://www.cnblogs.com/coolicer/p/2819109.html