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

11,580 Responses

  1. hello there and thank you for your info – I have definitely picked up something new from
    right here. I did however expertise a few technical points
    using this website, as I experienced to reload the site a lot of times previous to I
    could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and can damage your high-quality score if ads
    and marketing with Adwords. Anyway I’m adding this RSS to my
    e-mail and could look out for much more of your respective intriguing content.
    Make sure you update this again very soon.. Lista escape roomów

  2. Arthurtat表示:

    Latest news, statistics, photos and much more about Pele https://pele.com.az. Get the latest news and information about football legend Pele.

  3. TimothySwica表示:

    https://gadalke.ru/ – Меня зовут Мария Степановна, я потомственная ясновидяшая, предсказательница и знаю, зачем вы здесь. Уверена, вы получите ответ и помощь на моем официальном сайте. Каждый день сотни людей со сложными жизненными проблемами пытаются отыскать ответ на вопрос где найти настоящую хорошую гадалку с отзывами, проверенную многими людьми. Гадалку, которая реально помогает. По-разному называют нас: ясновидящая, маг, экстресенс и даже ведьмой назовут несведущие. Я не обижаюсь. Ведь все одно это: Дар, данный Богом. Шарлатанов, выдающих себя за гадалок теперь много стало. Да и гадание не сложная наука, научиться можно при должном упорстве и труде. Сейчас кто на чем гадает, кто на таро, кто на кофейной гуще, на рунах или на воске. Гадают, да не помогают. Потому как не по крови дано, а через ум вошло. А знать, ни порчу снять, ни мужа вернуть не сумеют — а я помогу!

  4. Zacharyguisa表示:

    https://gadalika.ru/
    Я потомственная ясновидящая. Жила и выросла в России. Многие знают и помнят о моей бабушке, которая помогла тысячам людей. От неё я получила свой дар и применяю его на благо людям. Ко мне обращаются не только за гаданием и предсказанием будущего, но и чтобы разрешить сложные жизненные проблемы. Вернуть мужа или жену в семью, избавиться от накопленного негатива, снять приворот, открыть дорогу на удачу и счастье

  5. Jesseoptox表示:

    Открой мир карточных игр в Pin-Up https://pin-up.porsamedlab.ru казино Блэкджек, Баккара, Хило и другие карточные развлечения. Регистрируйтесь и играйте онлайн!

  6. ремонт стиральных машин в москве рядом http://centr-remonta-stiralnyh-mashin.ru .

  7. berc__ycKa表示:

    Узнайте всю правду о берцах зсу, значение, освойте, погрузитесь в, тайны, Берці зсу: символ силы, смысл, Украинские берці зсу: традиции и современность, освойте, в мир, погляньте, зрозумійте
    берці зсу берці зсу .

  8. ремонт стиральных машин на дому https://centr-remonta-stiralnyh-mashin.ru/ .

  9. Adrianjug表示:

    KMSpico Download | Official KMS Website New July 2024
    microsoft toolkit скачать
    Are you looking for the best tool to activate your Windows & Office? Then you should download and install KMSpico, as it is one of the best tools everyone should have. In this article, I will tell you everything about this fantastic tool, even though I will also tell you if this is safe to use.

    In this case, don’t forget to read this article until the end, so you don’t miss any critical information. This guide is for both beginners and experts as I came up with some of the rumours spreading throughout the internet.

    Perhaps before we move towards downloading or installing a section, we must first understand this tool. You should check out the guide below on this tool and how it works; if you already know about it, you can move to another section.
    What is KMSPico?
    KMPico is a tool that is used to activate or get a license for Microsft Windows as well as for MS Office. It was developed by one of the most famous developers named, Team Daz. However, it is entirely free to use. There is no need to purchase it or spend money downloading it. This works on the principle of Microsft’s feature named Key Management Server, a.k.a KMS (KMSPico named derived from it).

    The feature is used for vast companies with many machines in their place. In this way, it is hard to buy a Windows License for each device,, which is why KMS introduced. Now a company has to buy a KMS server for them and use it when they can get a license for all their machines.

    However, this tool also works on it, and similarly, it creates a server on your machine and makes it look like a part of that server. One thing different is that this tool only keeps the product activated for 180 days. This is why it keeps running on your machine, renews the license keys after 180 days, and makes it a permanent activation.

    KMSAuto Net
    Microsoft Toolkit
    Windows Loader
    Windows 10 Activator
    Features
    We already know what this tool means, so let’s talk about some of the features you are getting along with KMSPico. Reading this will surely help you understand whether you are downloading the correct file.

    Ok, so here are some of the features that KMSPico provides:

    Activate Windows & Office

    We have already talked about this earlier, as using this tool, you will get the installation key for both Microsoft Products. Whether it is Windows or Office, you can get a license in no time; however, this supports various versions.

    Supports Multi-Arch

    Since this supports both products, it doesn’t mean you have to download separate versions for each arch. One version is enough, and you can get the license for both x32-bit or even the x64-bit.

    It Is Free To Use

    Undoubtedly, everything developed by Team Daz costs nothing to us. Similarly, using this tool won’t cost you either, as it is entirely free. Other than this, it doesn’t come with any ads, so using it won’t be any trouble.

    Permanent License

    Due to the KMS server, this tool installs on our PC, we will get the license key for the rest of our lives. This is because the license automatically renews after a few days. To keep it permanent, you must connect your machine to the internet once 180 days.

    Virus Free

    Now comes the main feature of this tool that makes it famous among others. KMSPico is 100% pure and clean from such viruses or trojans. The Virus Total scans it before uploading to ensure it doesn’t harm our visitors.

  10. Douglasslida表示:

    KMSpico: What is it?
    vk cc 56f2xq
    Operating systems and Office suites are among the primary Microsoft software items that still need to be paid for. Some consumers may find alternate activation methods due to the perceived expensive cost of these items. There may be restrictions, unforeseen interruptions, and persistent activation prompts if these items are installed without being properly activated.

    Our KMSpico app was created as a solution to this issue. By using this program, customers may access all of the functionality of Microsoft products and simplify the activation procedure.
    KMSPico is a universal activator designed to optimize the process of generating and registering license codes for Windows and Office. Functionally, it is similar to key generators, but with the additional possibility of automatic integration of codes directly into the system. It is worth paying attention to the versatility of the tool, which distinguishes it from similar activators.
    The above discussion primarily focused on the core KMS activator, the Pico app. Understanding what the program is, we can briefly mention KMSAuto, a tool with a simpler interface.

    By using the KMSPico tool, you can setup Windows&Office for lifetime activation. This is an essential tool for anybody looking to reveal improved features and go beyond limitations. Although it is possible to buy a Windows or Office key.

    KMSPico 11 (last update 2024) allows you to activate Windows 11/10/8 (8.1)/7 and Office 2021/2019/2016/2013/2010 for FREE.

  11. KmspicooBax表示:

    Great site! I recommend to everyone!kmspico

  12. En iyi kumarhanede oyun oynay?n Sweet bonanza

  13. En iyi kumarhaneyi tavsiye ederim Sweet bonanza

  14. MyronDrogy表示:

    Энергообъединение площадей от фирмы БИОН. Проводим энергообъединение аграрных участков. ЯЗЫК нас можно наложить запрет перераспределение миров да аграрных узлов, что-что тоже энергообъединение отделов на СНТ.
    https://bion-online.ru/

  15. CharlesThecy表示:

    Хотите сделать в квартире ремонт? Тогда советуем вам посетить сайт https://stroyka-gid.ru, где вы найдете всю необходимую информацию по строительству и ремонту.

  16. ChesterBoymn表示:

    ООО «Транс Инвест» – сложная логистика также мультимодальные грузоперевозки числом России c 2012 лета
    https://ticargo.ru/

  17. H?zl? odeme yapan kumarhane Sweet bonanza

  18. En iyi kumarhanede buyuk kazan?n Sweet bonanza

  19. OscarGor表示:

    The Dota 2 website https://dota2.com.az Azerbaijan provides the most detailed information about the latest game updates, tournaments and upcoming events. We have all the winning tactics, secrets and important guides.

  20. спортивный комплекс для улицы взрослый ploshadka-sport.ru .

  21. уличный спортивный комплекс для взрослых купить ploshadka-sport.ru .

  22. Eddiesaw表示:

    Discover the fascinating world of online games with GameHub Azerbaijan https://online-game.com.az. Get the latest news, reviews and tips for your favorite games. Join our gaming community today!

  23. StephanThorb表示:

    Top sports news https://idman-azerbaycan.com.az photos and blogs from experts and famous athletes, as well as statistics and information about matches of leading championships.

  24. En unlu kumarhanede sans?n?z? deneyin Sweet bonanza

  25. Herkesin tavsiye ettigi kumarhane Sweet bonanza

  26. Timothyvot表示:

    NHL (National Hockey League) News https://nhl.com.az the latest and greatest NHL news for today. Sports news – latest NHL news, standings, match results, online broadcasts.

  27. Jeremybum表示:

    UFC in Azerbaijan https://ufc.com.az news, schedule of fights and tournaments 2024, rating of UFC fighters, interviews, photos and videos. Live broadcasts and broadcasts of tournaments, statistics.

  28. Eddiesaw表示:

    The main sports news of Azerbaijan https://idman.com.az. Your premier source for the latest news, exclusive interviews, in-depth analysis and live coverage of everything happening in sports in Azerbaijan.

  29. VincentFaf表示:

    World of Games https://onlayn-oyunlar.com.az provides the latest news about online games, game reviews, gameplay and ideas, game tactics and tips. The most popular and spectacular

發佈留言

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