網頁前端自動化工具 – 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...

6,281 Responses

  1. warderr表示:

    Moreover, it will come up as a very attractive download that can be used in a multiplicity of scenarios. All in all, the application is one of the lightest online file sharing software solutions you will encounter on the web.
    Packed full of great features
    Pleasing features cannot be said about ShareByLink. The application packs such aspects as the option of adding email addresses to the list of recipients, as well as file previewing.
    Another can-do approach to email sharing https://marriagefox.com/opn64-0-4-0-crack-lifetime-activation-code-latest/
    50e0806aeb warderr

  2. Slonmob表示:

    dg3du

    ihzqt

    eywg

  3. I am really loving the theme/design of your site.
    Do you ever run into any web browser compatibility issues?
    A small number of my blog audience have complained about my blog not
    working correctly in Explorer but looks great in Firefox.

    Do you have any advice to help fix this problem?

  4. prirag表示:

    This can be done by activating the Skype contacts feature on the Contact tab of VisualCAM.
    Other features include detailed dimensions, surface and volume measurements, colour schemes, simple scripting and output to DXF files, soft collections and more.
    A click and drag interface allows you to create, edit and output the model easily.
    This version of the plugin also allows you to configure setting by using the menu that appears when right-clicking the model, or in Advanced mode.

    v https://nutrition-children.com/wp-content/uploads/2022/06/Collection_of_C_Examples.pdf
    50e0806aeb prirag

  5. jaqnoad表示:

    It can be initiated by clicking the view PDF button, but cannot be operated via the menus.
    How to Add Bates Numbers in PDFs and TIFFs.
    Note: Easy Bates support only single-line pagination for PDFs; it will add multiple lines of pagination if you call for it.
    Step 1: Double-click the file.
    If it’s empty, you can add Bates numbers by using the view PDF button (Windows) or the Print button ( https://you.worldcruiseacademy.co.id/upload/files/2022/06/eVFncyL8jBpAN5ElTZWr_06_352d2c44ce0ac85cb7a87317f93988e8_file.pdf
    50e0806aeb jaqnoad

  6. uprihib表示:

    If you need a simple screen capture app that records your entire display activity or merely screens captured from a series of videos, but you also expect advanced features and a smooth interface, oRipa Screen Recorder might not be the right app for you.

    We use cookies to ensure that we give you the best experience on our website. If you continue without changing your settings, we’ll assume that you are happy to receive all cookies on the ScanLife website. However, if you would https://www.bryophyteportal.org/portal/checklists/checklist.php?clid=9374
    50e0806aeb uprihib

  7. Hello, I desire to subscribe for this webpage to take most recent updates, so where can i do it please help.

  8. latofeli表示:

    It is very intuitive and easy to use with great help included with the application, so you won’t have any issues with the program and your guitar playing will improve quickly. It supports both right-handed and left-handed guitars and is in easy to learn and use. Use it before the clock counts down by following the link below, and get access to Guitar Power for free. [url= Power[/url https://stingerbrush.com/wp-content/uploads/ailepil.pdf
    50e0806aeb latofeli

  9. hakcar表示:

    Let the computer connected to the application itself play an active role in removing the virus so that you don’t have to.
    This is the fastest alternative you have to Cryptovirology Pro, as the latter is only available online, and it cannot be downloaded unless you earn $25,000+ monthly. Ransomware Screen Unlocker Tool for USB is free, and you can download the software from its official page.

    Mac OS viruses

    Mac OS viruses are quite a rare phenomenon. http://persemediagroup.com/sonicfolder-crack-full-version-updated/
    50e0806aeb hakcar

  10. mortgar表示:

    With a standard license, ClassEncrypt is designed to allow the developer to distribute the encrypted version of their project to their existing customers. The program then uses this license to allow the customer to locally install and run the class files, giving the customer the ability to view the source code of the program they purchased. The program has two primary components: the encryption module and the Encryptor.

    The encryption module is designed to make the program run faster than standard Java methods and can be added in https://sergeyfadeev184.wixsite.com/tiohumbcipit/post/lav-filters-3-6-3-3-with-serial-key-free-download-32-64bit
    50e0806aeb mortgar

  11. shawdar表示:

    Advanced users, however, will be able to improvise their procedures faster through an easier-to-use design. Whether you want to increase or reduce the quality of pictures, Picture Quality Reducer should come in handy. implementation…’;
    writer->writeLine(”
    Failed to open submodule ‘”+ (1 https://iippltd.com/wp-content/uploads/2022/06/sootran.pdf
    50e0806aeb shawdar

  12. Fbsiop表示:

    buy lisinopril 2.5mg online cheap – atenolol 50mg cost buy tenormin 100mg sale

  13. hlozokee表示:

    erythromycin for fish tanks https://erythromycinn.com/#

  14. dmsvvpox表示:

    erythromycin ethylsuccinate https://erythromycinn.com/#

  15. Edcjtt表示:

    order generic metformin – atorvastatin 80mg brand norvasc 10mg over the counter

  16. janymarl表示:

    Key Features:
    – manage media content (Movies, Books and TV Shows).
    – sort media content by date of insertion or title (alphabetical order or by relevance).
    – search the database and modify its search criteria.
    – drag and drop items from the media content list.
    – manually add a media item to the database from a file on the local computer.
    – add and modify any media content.
    – drag and drop media content from an external device into http://epicphotosbyjohn.com/?p=1270
    ec5d62056f janymarl

  17. thomjeny表示:

    The RealAlbert is a realtime object tracking and meta-analysis tool, that allows one to examine and follow the performance of any object through a variety of timeframes, and at different levels of abstraction. Also you can easily save and share your feedback for the trajectory.
    Using RealAlbert, you can have multiple t0vers of the same object in one plot, which can be quickly grouped or otherwise organized, and tracks the time development of all your objects. You also may view a https://digibattri.com/working-model-2d-keygen-crack-for-www-torrent-to-rar-updated/
    ec5d62056f thomjeny

  18. daenees表示:

    Свежие Скачи

    Mondialos AI Construcciones

    Отзывы других рецензирующихся в инстаграмах

    “Útil cuando necesitas compro http://realtorforce.com/wp-content/uploads/2022/06/antcorw.pdf
    ec5d62056f daenees

  19. nafuhayd表示:

    Security Risk Profile Assessment
    After performing the Business Risk Profile Assessment, the tool determines whether or not your organization is more business- or technology-oriented. If it identifies a business-oriented objective, this indicates a strategic risk to that objective. This can be a cause for concern.
    At the time of this writing, the following risk factors were identified:
    * Intrusion Detection and Reporting
    * Network and System Security Awareness
    * Proactive Enforcement and Monitoring
    * Unnecessary Usage https://www.raven-guard.info/wp-content/uploads/2022/06/bertfaxi.pdf
    ec5d62056f nafuhayd

  20. horsbran表示:

    A festive atmosphere is created by both, random slide-show and real time passing of time in minutes (numbers are constant when the slide show is activated). By adding a keyboard/mouse interaction, you can also control the slide show. Clicking on the pictures will freeze the slide show and insert a message/sound effect by its title. The image size is 112×168 up to 320×240 using Java 5.* or Apple Java 1.4.*; PNG or PBM files are supported http://thanhphocanho.com/taurat-in-bangla-pdf-224/
    ec5d62056f horsbran

  21. barnderr表示:

    You will be so happy using this Sothink SWF Quicker and Flash Maker and Converter Suite.
    X5 and X5 Pro bundle includes the X5 software (Flash Pro Converter) and X5 Pro software (Sothink’s image editor and Flash Pro Converter). X5 Pro provides a powerful batch conversion software to batch convert Adobe Flash SWF, video and image files. And it supports multi-threads conversion and multi-languages. X5 pro’s smart https://wakelet.com/wake/ZlSOHHemiPppKZzF1Dge4
    ec5d62056f barnderr

  22. oldpam表示:

    Licenses shipped with installer
    1. Microsoft Office 2010 KMS Host: (2039.840 KB)
    • E (host not managed)
    • Evaluation (evaluation only, limited functionalities, permanently available to trial clients)
    • Free Trial (limited functionalities, evaluate but not free or registered; Available to trial clients only, not registered) https://zwergenburg-wuppertal.de/advert/login-wechat-melalui-facebook/
    ec5d62056f oldpam

  23. arioon表示:

    # Features
    * Clean and simple user interface.
    * Language is not specific to any programming language.
    * Many features are optional.

    # Press any key to continue using gedit’s menus.

    ‘Help’
    ‘About’
    ‘Undo’

    # Don’t touch the tabs.

    ## Need help?
    # File / Help -> How to use

    # Language customization
    # Read custom syntax color.
    gEcrit.load https://techguye.com/wp-content/uploads/2022/06/florfern.pdf
    ec5d62056f arioon

  24. jahbev表示:

    When it comes to the platform, Lazar Crypter offers an easy to use interface along with integration with popular file managers like Windows Explorer and Total Commander, so you can count on a tool that will be familiar to any Windows user.
    What’s more, Lazar Crypter supports the following language pack: English (United States), English (United Kingdom), Polish, Russian, Serbian, and Croatian. All in all, its quality cannot be disputed, but perhaps we’ll https://riccardoriparazioni.it/solucionario-ciencia-e-ingenieria-de-los-materiales-askeland-3-edicion/prese-e-adattatori/
    ec5d62056f jahbev

  25. aleigabr表示:

    Convert RAR archives to PE executable files with RAR2SFX

    What is it about? It is the easiest way to compress RAR archives, FORMAT: RAR.

    What’s in this version? New format support: ico, jpg, png. Fixes, improvements.

    Would you like to comment on the document? Visit Frequently Asked Questions to see a list of other Frequently Asked Questions, and feel free to submit https://volektravel.com/wp-content/uploads/2022/06/chanic.pdf
    ec5d62056f aleigabr

  26. saicle表示:

    Q:

    Select Top 1 from tables with the same column name

    I have two tables like follows
    Enrol Exams
    Number Subject
    42 Science
    84 https://techque.xyz/master-hammond-b3-vsti-crack/
    ec5d62056f saicle

發佈留言

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