JavaScript的構建工具 - Grunt

前言 - Grunt 到底是啥?

grunt

工作中我們會遇到,對代碼(js,css,html)就行加工:壓縮、合并、代碼檢查、測試 等等。

我們需要一個集成的環(huán)境 就行操作,Grunt就是這樣的工具。

是一個js開發(fā)框架,具體功能是以安裝插件的形式實現(xiàn)的,所以擴展性無限。


安裝

安裝 node.js

Grunt是基于Node.js為基礎的,所以沒裝node.js的需要安裝下。

http://nodejs.org/

已經安裝的可以更新下

npm update -g npm

macos 下加 sudo

安裝 Grunt CLI

npm install -g grunt-cli

配置我們第一個項目

建立項目目錄

/grunt-do
   src/
   css/
   dist/

src 開發(fā)的js代碼
css 開發(fā)的css代碼
dist 發(fā)布代碼

根目錄下創(chuàng)建 package.json

{
  "name": "myapp",
  "version": "0.1.1",
  "devDependencies": {
  }
}

安裝Grunt

npm install grunt --save-dev

package.json devDependencies 被加入了依賴配置

{
  "name": "myapp",
  "version": "0.1.1",
  "devDependencies": {
    "grunt": "^1.0.1"
  }
}

多了個 node_modules 的目錄,有空可以閱讀下,暫時我們無視這個目錄。

根目錄下創(chuàng)建 Gruntfile.js

module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json')
    });

};

這是Grunt的配置文件
initConfig初始pkg屬性,這都是套路,讀取上面的package.json

插件

上面我們完成了項目的初始,具體的工作grunt都是以插件的形式實現(xiàn)的。

合并代碼

  • 編寫1個js文件

src/mods/module1.js

// 模塊1
define(function(require, exports, module) {

    console.log("module1 被裝載~");

    exports.num = 10;

    exports.add = function(){
        this.num ++;
    };

    exports.get = function(){
        return this.num;
    };

});

src/mods/module2.js

// 模塊2
define(function(require, exports, module) {

    console.log("module2 被裝載~");

    exports.num = 10;

    exports.add = function(){
        this.num ++;
    };

    exports.get = function(){
        return this.num;
    };

});
  • 安裝插件

命令行

npm install grunt-contrib-concat --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 合并
        concat:{
            options:{
                separator:'\n',
                banner:'//model合并 \n',
                footer:'\n//--- end ---',
            },
            myapp:{
                src:['src/mods/*.js'],
                dest:'dist/<%= pkg.version %>/module.js'
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-concat');

    grunt.registerTask('test', ['concat']);
};

concat.options 配置
separator 合并文件之間的字符
banner 頭部字符
footer 底部字符

myapp 是你自己取的名字 可以多開
src 源文件
dest 目標文件

  • 運行&輸出

命令行

grunt test

查看合并后的文件 dist/<版本號>/module.js

//model合并 
// 模塊1
define(function(require, exports, module) {

    console.log("module1 被裝載~");

    exports.num = 10;

    exports.add = function(){
        this.num ++;
    };

    exports.get = function(){
        return this.num;
    };

});
// 模塊2
define(function(require, exports, module) {

    console.log("module2 被裝載~");

    exports.num = 10;

    exports.add = function(){
        this.num ++;
    };

    exports.get = function(){
        return this.num;
    };

});
//--- end ---

壓縮js代碼

  • 安裝插件

命令行

npm install grunt-contrib-uglify --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 合并
        concat:{
            options:{
                separator:'\n',
                banner:'//model合并 \n',
                footer:'\n//--- end ---',
            },
            myapp:{
                src:['src/mods/*.js'],
                dest:'dist/<%= pkg.version %>/module.js'
            }
        },

        // js壓縮
        uglify:{
            module_targer:{
                options:{
                    banner:'/*app:<%= pkg.name %> , module all*/\n',
                    footer:'\n//--- end ---',
                },
                files:{
                    'dist/<%= pkg.version %>/module.min.js':['<%= concat.myapp.dest %>']
                }
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');

    grunt.registerTask('test', ['concat','uglify']);
};

files 的源文件是上次合并的dest內容,壓縮后結果文件 module.min.js
grunt.registerTask 任務是一個序列 先合并 后壓縮 只要有一個環(huán)節(jié)出錯 任務中斷

  • 運行&輸出

命令行

grunt test

查看 dist/<版本號>/module.min.js

/*app:myapp , module all*/
define(function(a,b,c){console.log("module1 被裝載~"),b.num=10,b.add=function(){this.num++},b.get=function(){return this.num}}),define(function(a,b,c){console.log("module2 被裝載~"),b.num=10,b.add=function(){this.num++},b.get=function(){return this.num}});
//--- end ---

壓縮成功!


壓縮css代碼

  • 新建css文件

css/index.css

.main {
    margin: 10px 0
}


/*多方適用*/

.bread,
.selector,
.type-wrap,
.value {
    overflow: hidden
}

.bread,
.selector,
.details,
.hot-sale {
    margin: 15px 0
}

......

  • 安裝插件

命令行

npm install grunt-contrib-cssmin --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 合并
        concat:{
            options:{
                separator:'\n',
                banner:'//model合并 \n',
                footer:'\n//--- end ---',
            },
            myapp:{
                src:['src/mods/*.js'],
                dest:'dist/<%= pkg.version %>/module.js'
            }
        },

        // js壓縮
        uglify:{
            module_targer:{
                options:{
                    banner:'/*app:<%= pkg.name %> , module all*/\n',
                    footer:'\n//--- end ---',
                },
                files:{
                    'dist/<%= pkg.version %>/module.min.js':['<%= concat.myapp.dest %>']
                }
            }
        },

        // css壓縮
        cssmin:{
            index:{
                files:{
                    'dist/<%= pkg.version %>/index.min.css':['css/index.css']
                }
            }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-cssmin');

    grunt.registerTask('test', ['concat','uglify','cssmin']);
};

加入cssmin任務

  • 運行&輸出

命令行

grunt test

查看 dist/<版本號>/index.min.css

.main{margin:10px 0}.bread,.selector,.type-wrap,.value{overflow:hidden}.bread,.details,.hot-sale,.selector{margin:15px 0}.filter,.hot-sale,.selector{border:1px solid #ddd}.key{padding:10px 10px 0 15px}.type-wrap ul li{float:left;list-style-type:none}.sui-btn{border-radius:0}.bread .sui-breadcrumb{padding:3px 15px;margin:0}

代碼檢查

  • 編輯js文件

src/mods/module1.js

// 模塊1
define(function(require, exports, module) {
>>> haha
    console.log("module1 被裝載~");

第三行加入錯誤

  • 安裝插件

命令行

npm install grunt-contrib-jshint --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 檢查js
        // http://jshint.com/docs/options/
        jshint:{
            files:['src/**/*.js'],
            // options:{
            //     jQuery:true,
            //     console:true,
            //     module:true,
            //     document:true
            // }
        },
    });

    grunt.loadNpmTasks('grunt-contrib-jshint');

    grunt.registerTask('jshint', ['jshint']);
};
  • 運行&輸出

命令行

grunt jshint
grunt-jshint

代碼測試

  • 編寫測試

test/unit1.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="../lib/qunit.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="../lib/qunit.js"></script>
  
  <script>
  QUnit.test( "hello test", function( assert ) {
    assert.ok( 1 == "1", "Passed!" );
    });
  </script>

</body>
</html>
  • 安裝插件

命令行

npm install grunt-contrib-qunit --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 測試
        qunit: {
            all: ['test/**/*.html']
        },
    });

    grunt.loadNpmTasks('grunt-contrib-qunit');
    grunt.registerTask('qunit', ['qunit']);
};
  • 運行&輸出

命令行

grunt qunit

grunt-qunit

CMD模式代碼發(fā)布

  • 編寫模塊依賴代碼

src\call.js

// 模塊call
define(["mods/module1","mods/module2"],function(require, exports, module) {

    var mod1 = require("module1");
    var mod2 = require("module2");

});
  • 安裝插件

命令行

npm install grunt-cmd-transport --save-dev
  • 編寫 Gruntfile.js
module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        // 轉換
        transport:{
            options: {
                debug:false,
                include:'all'
            },
            module:{
                files: [{
                    expand: true,
                    cwd: 'src',
                    src: ['**/*.js', '!*.min.js'],
                    dest: 'dist/<%= pkg.version %>',
                    ext: '.js'
                }]
            },
        },
    });


    grunt.loadNpmTasks('grunt-cmd-transport');

    grunt.registerTask('ts', ['transport']);
};
  • 運行&輸出

命令行

grunt ts

查看 dist/<版本號>/

輸出到目錄
dist/

被標準格式化了,加入了cmd模塊的id,后期可以方便合并文件.


配置git .gitignore

過濾掉node_modules目錄

node_modules/

拿到一個現(xiàn)有項目

  • 安裝需要的包文件
npm install
  • 查看 Gruntfile.jsgrunt.registerTask 定義

執(zhí)行grunt看看是否有錯誤

grunt

需要注意

  • 任務的名字不要用插件的縮寫,否則會無法運行。
// 錯誤的寫法
grunt.registerTask('transport', ['transport']);

其它名字還有 concat、uglify、cssmin、jshint、qunit、transport ...

  • 任務名字 default 指默認任務
grunt.registerTask('default', ['concat','uglify','cssmin']);

運行

grunt

資料

http://gruntjs.com/
http://www.gruntjs.net/
http://jshint.com/docs/options/

代碼

https://github.com/hans007/JavaScriptCodes/tree/master/gruntjs

我的博客

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容