網頁前端自動化工具 – Grunt

Grunt 網站截圖

Grunt 網站截圖



今天為各位介紹的是一個前端工程師所使用的自動化工具「Grunt」,為何我們要使用這個工具呢?其實使用這個工具的原因有很多,因為他的擴充模組(Plugin)也很多,不過今天馬老師從自動最小化(Minify)的角度來介紹這個工具該如何使用。

一般來說前端網頁開發不外乎HTML、CSS、Javascript這三種語法,而在開發完成之後,為了要節省流量,我們可能會把這三個檔案壓縮後再上傳到網站伺服器上,何謂壓縮請參考下圖:

未經壓縮的HTML檔

未經壓縮的HTML檔

經過壓縮的HTML檔

經過壓縮的HTML檔

未經壓縮的CSS檔

未經壓縮的CSS檔

經過壓縮的CSS檔

經過壓縮的CSS檔

未經壓縮的JS檔

未經壓縮的JS檔

經過壓縮的JS檔

經過壓縮的JS檔

從上面的檔案可以觀察出在開發時我們為了閱讀的便利,常常會利用註解、空白…等來輔助,但真正發佈出去這些東西卻不是必要的,甚至在開發的時候我們為了方面會把CSS或JS拆成好幾個檔案,但發佈之後卻希望可以合併,但如果需要人工來做這件事,可想而知會有多麻煩,這個時候Grunt就會發揮效用了,設定好之後只要一個指令,他就可以幫我們做好這些動作,接下來就來看看該如何使用吧。

首先Grunt是一個基於node.js下的應用程序,所以必須先安裝node.js,安裝的部分並不難,從官網下載後直接執行安裝即可。

Node.js 官方網站 截圖

Node.js 官方網站 截圖

接下來可以參考Grunt網站中Getting Started的單元,或是跟著以下(以Windows為案例)的方式進行Grunt的安裝。

  1. 打開「命令提示字元」。
  2. 輸入「npm install -g grunt-cli」。
  3. 接下來就可以準備網頁專案資料夾了,如下圖所示,我的網頁專案資料夾簡單分成兩個:
    • src:所有開發檔案
    • public:發佈至網路上的檔案

      準備專案資料夾

      準備專案資料夾

  4. 這樣準備的目的應該很清楚,就是希望在src資料夾內以自己最習慣、最方便閱讀的方式來開發,而開發完畢之後可以把壓縮的檔案轉至public資料夾,上傳到伺服器上。

有關於網頁內容開發的部分,本篇文章就省略,所以可以看到上面圖檔中我已經準備好了HTML、CSS、JS各一個,直接進入利用Grunt開始做自動最小化的部分。

  1. 使用Grunt時,必須在網站根目錄建立兩個檔案:
    • package.json:Grunt的專案設定檔,其中可以包含專案名稱、作者、版本,所需要使用的Plugin…等,可以參考下面我的檔案。
    • Grunt.js:Grunt的執行腳本,以本案例來說就是要去哪個資料夾,壓縮哪些檔案後存放在哪邊,需在本檔案中指定。
      {
          "name": "gruntTest",
          "version": "0.1.0",
          "author": "Stanley Ma",
          "devDependencies": {
              "grunt": "~0.4.5",
              "grunt-contrib-htmlmin": "~0.4.0",
              "grunt-contrib-cssmin": "~0.13.0",
              "grunt-contrib-uglify": "~0.9.2"
          }
      }

      以上面的package.json檔案來說,定義了專案名稱、作者、版本以及所需要使用的Grunt版本(撰文時Grunt穩定版為0.4.5)和Plugin列表,因為開頭有提到,本案例以最小化的角度來介紹Grunt,所以用到的三個Plugin分別為:

      • grunt-contrib-htmlmin:最小化HTML檔。
      • grunt-contrib-cssmin:最小化CSS檔。
      • grunt-contrib-uglify:最小化JS檔。
  2. 接下來利用Grunt的專案設定檔來安裝所需要的Grunt和各個外掛,利用「命令提示字元」進入網頁專案的根目錄,輸入「npm install」,他就會在專案資料夾中安裝好所有需要的Plugin。

    安裝 Grunt 後的專案資料夾

    安裝 Grunt 後的專案資料夾

  3. 接下來就要開始準備撰寫Grunt.js的執行腳本,大家可以參考我的專案檔案寫法:
    module.exports = function (grunt) {
    
        grunt.initConfig({
            htmlmin: {
                Target: {
                    options: {
                        removeComments: true,
                        collapseWhitespace: true,
                        removeEmptyAttributes: true,
                    },
                    files: {
                        'public/index.html': 'src/index.html',
    
                    }
                }
            },
    
            cssmin: {
                target: {
                    files: {
                        'public/index.css': 'src/index.css'
                    }
                }
            },
    
            uglify: {
                target: {
                    files: {
                        'public/index.js': 'src/index.js'
                    }
                }
            }
    
        });
    
        grunt.loadNpmTasks('grunt-contrib-htmlmin');
        grunt.loadNpmTasks('grunt-contrib-cssmin');
        grunt.loadNpmTasks('grunt-contrib-uglify');
    
        grunt.registerTask('default', ['htmlmin', 'cssmin', 'uglify']);
    
    };

    這樣的寫法會讓Grunt把在src裡面的三個檔案,分別壓縮後複製一份到public的資料夾中,確定資料夾和檔案無誤之後,繼續下一步動作。

  4. 利用「命令提示字元」進入網頁專案的根目錄,輸入「grunt」之後,出現以下的畫面表示成功。

    Grunt 執行成功

    Grunt 執行成功

  5. 本案例利用三個Grunt的Plugin完成,分別是:「grunt-contrib-htmlmin」、「grunt-contrib-cssmin」、「grunt-contrib-uglify」,其實這三個外掛都有一些其他的參數,另外也可以進行多檔案的批次轉換以及檔案合併…等等功能,建議有需要的同學可以到Plugin各自的網站上去看看使用方式。

附帶一提,一開始就有提到關於Grunt自動化的Plugin非常多,本文僅用到了三個,這裡有Plugin的列表,對這方面有興趣的同學們也歡迎到網站上看更多相關的自動化功能。

You may also like...

23,900 Responses

  1. Ce site表示:

    Having read this I thought it was rather informative. I appreciate you spending some time and effort to put this short article together. I once again find myself personally spending way too much time both reading and posting comments. But so what, it was still worth it!

  2. Victorprima表示:

    Outstanding service, no matter where you’re located.
    cost cheap cipro without prescription
    I’m always informed about potential medication interactions.

  3. Each part, including the waxing moon, full moon, waning moon, and new moon, is related to particular intentions and spellwork.

  4. WalterCherm表示:

    Their international health forums provide crucial insights.
    https://lisinoprilpharm24.top/
    A reliable pharmacy that connects patients globally.

  5. DonaldTyclE表示:

    Impacto mecanico
    Dispositivos de ajuste: esencial para el rendimiento fluido y productivo de las dispositivos.

    En el entorno de la avances avanzada, donde la productividad y la estabilidad del aparato son de gran significancia, los dispositivos de calibración juegan un función fundamental. Estos equipos especializados están desarrollados para equilibrar y estabilizar piezas rotativas, ya sea en maquinaria de fábrica, vehículos de desplazamiento o incluso en electrodomésticos de uso diario.

    Para los profesionales en reparación de equipos y los especialistas, manejar con equipos de balanceo es importante para proteger el funcionamiento estable y seguro de cualquier dispositivo giratorio. Gracias a estas opciones avanzadas avanzadas, es posible limitar sustancialmente las sacudidas, el sonido y la esfuerzo sobre los sujeciones, mejorando la longevidad de partes costosos.

    Igualmente trascendental es el tarea que desempeñan los sistemas de equilibrado en la asistencia al consumidor. El soporte profesional y el reparación constante empleando estos sistemas facilitan brindar servicios de gran nivel, elevando la contento de los usuarios.

    Para los propietarios de emprendimientos, la contribución en unidades de balanceo y medidores puede ser fundamental para incrementar la efectividad y productividad de sus equipos. Esto es principalmente importante para los inversores que administran pequeñas y modestas empresas, donde cada detalle es relevante.

    Además, los equipos de calibración tienen una amplia implementación en el área de la prevención y el monitoreo de nivel. Facilitan identificar potenciales fallos, previniendo mantenimientos costosas y perjuicios a los sistemas. Incluso, los resultados obtenidos de estos equipos pueden utilizarse para maximizar procedimientos y aumentar la presencia en plataformas de consulta.

    Las campos de uso de los equipos de ajuste abarcan variadas sectores, desde la producción de transporte personal hasta el seguimiento del medio ambiente. No importa si se refiere de extensas producciones industriales o reducidos talleres domésticos, los sistemas de balanceo son fundamentales para promover un desempeño óptimo y sin riesgo de interrupciones.

  6. Victorprima表示:

    An excellent choice for all pharmaceutical needs.
    gabapentin interactions with ativan
    They’re globally connected, ensuring the best patient care.

  7. Jasonzitte表示:

    The one-stop solution for all international medication requirements.
    how to get cheap lisinopril pills
    Their international health workshops are invaluable.

  8. Victorprima表示:

    Their patient education resources are top-tier.
    conversion of gabapentin to pregabalin
    They always have the newest products on the market.

  9. 1win_ctKr表示:

    1вин сайт онлайн http://1win12.am .

  10. WalterCherm表示:

    A true champion for patients around the world.
    https://cipropharm24.top/
    Drug information.

  11. MAN CLUB表示:

    This blog was… how do I say it? Relevant!! Finally I’ve found something which helped me. Thanks.

  12. 1win_sxPr表示:

    1вин официальный регистрация https://1win11.am/ .

  13. Victorprima表示:

    The staff always goes the extra mile for their customers.
    how can i get cheap clomid price
    They have strong partnerships with pharmacies around the world.

  14. It is useful for these people who are making their career and wish to get success.

  15. Jasonzitte表示:

    They simplify the complexities of international prescriptions.
    can you get cheap cytotec without a prescription
    Their patient care is unparalleled.

  16. I just wanted to thank you again for this amazing site you have built here. Its full of useful tips for those who are definitely interested in this subject, especially this very post. Your all so sweet and also thoughtful of others and reading the blog posts is a good delight to me. And thats a generous surprise! Jeff and I are going to have excitement making use of your points in what we must do in the near future. Our listing is a distance long and tips is going to be put to fine use. Prishtina Reisen

  17. After study several of the web sites on your own internet site now, and I really appreciate your technique of blogging. I bookmarked it to my bookmark internet site list and will be checking back soon. Pls consider my website likewise and told me if you agree.

  18. Youre so cool! I dont suppose Ive read anything in this way prior to. So nice to locate somebody by original thoughts on this subject. realy thank you for beginning this up. this fabulous website can be something that is required on the net, an individual with a bit of originality. helpful project for bringing new things to your internet!

  19. Victorprima表示:

    A pharmacy that genuinely cares about community well-being.
    how long until gabapentin is out of your system
    The team always keeps patient safety at the forefront.

  20. WalterCherm表示:

    The widest range of international brands under one roof.
    https://cytotecpharm24.top/
    Their worldwide reach ensures I never run out of my medications.

  21. VA88表示:

    Nice post. I learn something new and challenging on sites I stumbleupon every day. It will always be helpful to read articles from other authors and practice something from their sites.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。