快速開發Grunt插件----壓縮js模板

前言

Grunt是一款前端構建工具,幫助咱們自動化搭建前端工程。它能夠實現自動對js、css、html文件的合併、壓縮等一些列操做。Grunt有不少插件,每一款插件實現某個功能,你能夠經過npm命名去下載插件,而後使用它們。關於grunt的使用以及配置,滷煮不打算在此介紹。本篇博文重點要講的是如何快速開發一款自定義的grunt插件。由於滷煮在打包合併代碼的時候發現了沒法將html和js混合的文件進行壓縮處理,爲此滷煮也翻了不少資料,沒查找到理想的解決方案。在山窮水復之時,硬着頭皮本身開發了一個簡單的插件。在這裏分享出來給諸位,望對正在使用grunt構建工具的諸君能有所幫助。javascript

建立插件

1經過 npm install -g grunt-init 命令安裝 grunt-init 。css

2經過 git clone git://github.com/gruntjs/grunt-init-gruntplugin.git ~/.grunt-init/gruntplugin 命令安裝grunt插件模版。html

3在一個空的目錄中執行 grunt-init gruntplugin 。前端

4執行 npm install 命令以準備開發環境。java

在執行到第三步的時候會出現若干選擇讓你填寫,這些選項都是初始化插件時的配置選項。把你的插件名稱和github替換本地地址填上外其餘的均可以選擇默認。而後咱們獲得了一個默認的插件模塊工程目錄。以下所示:git

其中Gruntfile.js是當前模塊須要的依賴,你須要的是在tasks中的js文件中編寫本身的插件。github

編寫插件

一個插件是能夠配置的,在開發插件以前,你須要瞭解一些執行參數和配置。假設你的插件放入到了工程中去了,那麼在該工程的gruntfile文件中必須寫上要加載的插件而且給他參數,告訴這個插件怎麼樣處理哪些文件。此處仍然以壓縮js和html混合代碼的html文件爲例子,展現咱們編寫插件時的基礎配置:npm

module.exports = function(grunt) {

    // 構建任務配置
    grunt.initConfig({

        //讀取package.json的內容,造成個json數據
        pkg: grunt.file.readJSON('package.json'),
        //壓縮模板文件
        htmlmin: {
            options: {
                a:1,
                b:2,
                c:3
            },
            html: {
                expand: true,
                cwd: 'js/tpl/',
                src: ['*.html'],
                dest: 'js/html_min/'
            }
        }

    });

    // 加載指定插件任務
    grunt.loadNpmTasks('grunt-htmlmin');


    // 默認執行的任務
    grunt.registerTask('default', ['htmlmin']);

};

咱們能夠看到在配置文件中有了若干的配置項,那麼咱們在本身開發的htmlmin插件中怎麼樣讀取呢。對於options咱們能夠在本身的插件中用this.options獲取到,其餘html對象中的配置是直接做爲文件的默認屬性而引用的。json

/*
 * template-uglify
 * https://github.com/燒炭黨人-申包胥/grunt-plugin
 *
 * Copyright (c) 2016 chen.y
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks
//開始註冊任務
  grunt.registerMultiTask('htmlmin', 'uglify these html template', function() {
    // Merge task-specific and/or target-specific options with these defaults.此處即爲options中的參數默認配置項,上面的a b c都會傳入其中
    var options = this.options({
      punctuation: '',
      separator: ', '
    });

    // Iterate over all specified file groups.
    this.files.forEach(function(f) {
      // Concat specified files.
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(options.separator));

      // Handle options.src未文件內容的字符串
      src += options.punctuation;
      //此處爲添加的業務,將讀取到的文件內容壓縮
      src = src.replace(/\r\n/g, '').replace(/\s+/g, ' ').replace(/>\s+(?=<)/g, '$1');
      // 將處理後的文件存入目標位置 dest是上文中配置的路徑/js/html_min/
      grunt.file.write(f.dest, src);

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};

發佈插件

如今,你的基本的插件以及完成。經過本地測試後你能夠執行 npm publish命令將你建立的 Grunt 插件提發佈npm!爲了檢驗插件,咱們將一個html爲後綴名的html文件進行壓縮:api

<!--消費訂單-->
<script id="tplmenu" type="text/template">
	<footer class="bottom">
		<%for(var i=0; i<globalConfig.menu.length; i++){%>
		<div class="box <%if(globalConfig.menu[i].sub_button.length > 0){%>haschild<%}%>" data-url="<%=globalConfig.menu[i].url%>">
			<div><%=globalConfig.menu[i].name%></div>
			<%if(globalConfig.menu[i].sub_button.length > 0){%>
				<ul class="hidelist">
				<%for(var n=0; n<globalConfig.menu[i].sub_button.length; n++){%>
					<a href="<%=globalConfig.menu[i].sub_button[n].url%>"><%=globalConfig.menu[i].sub_button[n].name%></a>
				<%}%>
				</ul>
			<%}%>
		</div>
		<%}%>
	</footer>
</script>

配置gruntfile文件cwd:'source',src:['*.html'], dest:'target',執行grunt命令,獲得壓縮後的html:

<!--消費訂單--><script id="tplmenu" type="text/template"><footer class="bottom"><%for(var i=0; i<globalConfig.menu.length; i++){%><div class="box <%if(globalConfig.menu[i].sub_button.length > 0){%>haschild<%}%>" data-url="<%=globalConfig.menu[i].url%>"><div><%=globalConfig.menu[i].name%></div><%if(globalConfig.menu[i].sub_button.length > 0){%><ul class="hidelist"><%for(var n=0; n<globalConfig.menu[i].sub_button.length; n++){%><a href="<%=globalConfig.menu[i].sub_button[n].url%>"><%=globalConfig.menu[i].sub_button[n].name%></a><%}%></ul><%}%></div><%}%></footer></script>

參考文檔

http://www.gruntjs.net/creating-plugins

http://www.gruntjs.net/api/grunt

如何編寫grunt 插件

Grunt 插件開發與調式

相關文章
相關標籤/搜索