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

24,078 Responses

  1. Charleskepsy表示:

    canadian pharmacy world coupons https://easycanadianpharm.shop/# best canadian pharmacy online

  2. car call adas表示:

    The argumentation on the state of the country was compelling and well-structured. I found myself nodding along as I read.

  3. OLaneevige表示:

    Hi there, You have done a great job. I’ll definitely digg it and personally suggest to my friends. I am sure they will be benefited from this web site.

    Wyoming Valley Equipment LLC

  4. WilliamSed表示:

    About us
    Since its founding in 2020, EtherCode Innovation has demonstrated an outstanding level of expertise in smart contract development on the Ethereum platform. The EtherCode Innovation team brings together experienced developers whose knowledge and skills allow them to create reliable and innovative solutions for their clients
    eth honeypot code
    Mission
    We strive to ensure that every person interested in blockchain technologies can gain high-quality knowledge and skills. Our mission is to develop smart contracts that not only improve the functionality of the Ethereum network, but also contribute to the education and development of the developer community.

    Our services
    EtherCode Innovation specializes in creating various smart contracts within Ethereum. We develop innovative solutions for financial instruments, decentralized applications (DApps) and digital asset management systems. Our team has deep knowledge of the Solidity and Vyper programming languages, which allows us to create secure and efficient smart contracts.

    In addition, we provide free educational content for those who want to learn how to create tokens, including Honeypot tokens. Our materials cover all aspects of creating and deploying tokens on Ethereum, from basic concepts to complex technical details.

    Our contribution to the community
    We believe that education plays a key role in the development of the blockchain community. Therefore, we actively participate in various educational and communication initiatives. We also support various educational projects aimed at spreading knowledge about blockchain.

    Development prospects
    We are confident that blockchain technology will continue to transform the world, and we are committed to staying at the center of this process. Our team will continue to create innovative products, develop educational resources, and actively participate in the development of the Ethereum developer community.

    Finally, it is worth noting that EtherCode Innovation is committed to continuous development and innovation. The team is constantly researching new technologies and development methods to provide its clients with the most advanced solutions. Thanks to this approach, the company remains ahead of its time and continues to be in demand in the field of blockchain development.

    EtherCode Innovation is not just a company developing smart contracts on Ethereum. We are leaders in blockchain technology and education, and we invite you to join us on this exciting journey into the world of decentralization and innovation.

  5. Making hard to understand concepts readable is no small feat. It’s like you know exactly how to tickle my brain.

  6. car cal adas表示:

    I always learn something new from The posts. Thank you for the education!

  7. car cal adas表示:

    The dedication to high quality content shows. It’s like you actually care or something.

  8. Davidmoits表示:

    easy canadian pharm: easy canadian pharm – easy canadian pharm

  9. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon цены, можете посмотреть на сайте: ремонт фотоаппаратов canon цены
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. MichaelGeony表示:

    canadian online pharmacy no prescription https://familypharmacy.company/# Best online pharmacy

  11. car cal adas表示:

    The passion for the state of the country shines through the words. Inspiring!

  12. MichaelGeony表示:

    cheapest pharmacy to fill prescriptions with insurance http://easycanadianpharm.com/# canadian pharmacy 24h com safe

  13. adas car cal表示:

    This post is packed with insights on the state of the country I hadn’t considered before. Thanks for broadening my horizons.

  14. Davidmoits表示:

    top online pharmacy india: Mega India Pharm – MegaIndiaPharm

  15. Charleskepsy表示:

    canada pharmacy coupon http://easycanadianpharm.com/# easy canadian pharm

  16. car call adas表示:

    Unique perspective? Check. Making me rethink my life choices? Double-check.

  17. Круглосуточная поставка спиртного в Москве: комфорт либо проблема?

    Как это функционирует?

    Круглосуточная доставка спиртного в Москве осуществляется через многообразные службы:

    Интернет-сервисы: Профильные веб-сайты и программы, что предлагают широкий выбор алкогольных продуктов с поставкой в дом. Рестораны и пабы: Некоторые заведения, имеющие лицензию на реализацию спиртного, предоставляют доставку своей товаров в ночное время. Курьерские сервисы: Компании, которые сотрудничают с имеющими лицензию продавцами алкоголя и проводят поставку по требованию. Плюсы:

    Удобство: Возможность заказать любимый напиток, не выходя из дома, в любое время суток. алкоголь на дом москва – Сбережение времени: Не требуется тратить время на поход в магазин, особо в позднее время. Широкий ассортимент: Большой выбор спиртных напитков, в том числе необычные и особенные предложения. Шанс для вечеринок и мероприятий: Оперативная поставка дает возможность быстро пополнить запасы алкоголя, если это необходимо. Недостатки и споры:

    Правомерность: В России запрещена продажа алкоголя в ночное время (с 23:00 до 8:00). Сервисы поставки, которые предлагают круглосуточную доставку, часто применяют различные способы, которые способны оказаться незаконными. Употребление алкоголя: Простой получение к алкоголю в любое время может помогать росту потребления, что способен иметь отрицательные последствия на самочувствия. Проверка над реализацией несовершеннолетним: Существует опасность, что доставщики могут не контролировать лета покупателей, что способен вызвать к продаже спиртного несовершеннолетним.

  18. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт фотоаппаратов canon адреса, можете посмотреть на сайте: ремонт фотоаппаратов canon рядом
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  19. The writing is a go-to resource for me. Thanks for all the hard work on the state of the country!

  20. adas car cal表示:

    Thoroughly insightful read, or so I thought until I realized it was The expertise shining through. Thanks for making me feel like a novice again!

  21. MichaelGeony表示:

    pharmacy coupons https://easycanadianpharm.com/# easy canadian pharm

  22. WilliamDam表示:

    Aerodrome Finance: Unlocking Potential for Growth
    The world of aerodrome finance is pivotal for ensuring the efficient operation, enhancement, and expansion of aerodrome facilities globally. With the increasing demand for air travel, understanding aerodrome financial processes is more important than ever.
    aerodrome exchange
    Why Aerodrome Finance Matters
    Aerodrome finance plays a critical role in the lifespan of airport projects, providing necessary funding from initial development to ongoing management. Here are key reasons why it matters:

    Infrastructure Development: Secure financial backing enables the construction and maintenance of essential airport infrastructure.
    Operational Efficiency: Adequate funding ensures that airports can operate smoothly, adapting to technological advancements and logistical demands.
    Economic Growth: Airports serve as economic hubs; their development stimulates job creation and boosts local economies.
    Aerodrome Finance Strategies
    Various strategies can be employed to optimize aerodrome finance, ensuring both immediate and long-term benefits. Here are a few notable approaches:

    Public-Private Partnerships (PPP)
    These partnerships combine public sector oversight and private sector efficiency, leading to shared risks and rewards. They facilitate diverse financial resources and innovative solutions for airport projects.

    Revenue Diversification
    Exploring non-aeronautical revenue streams, such as retail concessions and property leases, can significantly bolster an airport’s financial resilience. Such diversification allows for a steady income flow independent of ticket sales.

    Sustainable Financing
    Adopting sustainable financial practices, including green bonds and ESG (Environmental, Social, and Governance) criteria, aligns with modern ecological standards and attracts environmentally conscious investors.

    Challenges and Opportunities
    While aerodrome finance offers numerous benefits, it also poses certain challenges. High capital costs, regulatory hurdles, and fluctuating passenger demands can impact financial stability. However, these challenges also present opportunities for innovation and improvement.

    Tech-Driven Solutions: Embracing technology like AI and predictive analytics can enhance decision-making and financial planning.
    Collaboration: Strengthening ties with stakeholders, including airlines and government agencies, can streamline financial operations and capital investments.
    Ultimately, the goal of aerodrome finance is to support the sustainable growth and modernization of airports, ensuring their pivotal role in global connectivity remains strong.

  23. Davidmoits表示:

    canada drugs online reviews: ed drugs online from canada – easy canadian pharm

  24. JeffreyDow表示:


    Временная регистрация в Москве – быстро и надежно!

    Нужна временная прописка для работы, учебы или оформления документов?
    Оформим официальную регистрацию в Москве всего за 1 день. Без очередей,
    с гарантией и юридической чистотой!

    1. Подходит для граждан РФ и СНГ
    2. Регистрация от 3 месяцев до 5 лет
    3. Легально, с внесением в базу МВД

    Работаем без предоплаты! Документы можно получить лично или дистанционно.
    Доступные цены, оперативное оформление!

    Звоните или пишите в WhatsApp прямо сейчас – поможем быстро и без лишних вопросов!
    Временная регистрация в Москве

  25. Charleskepsy表示:

    online pharmacy without prescription https://megaindiapharm.shop/# MegaIndiaPharm

  26. Davidmoits表示:

    Mega India Pharm: Mega India Pharm – MegaIndiaPharm

  27. Porterfax表示:

    xxl mexican pharm xxl mexican pharm xxl mexican pharm

  28. Porterfax表示:

    Mega India Pharm Mega India Pharm reputable indian online pharmacy

  29. MichaelGeony表示:

    canadian pharmacy discount code https://easycanadianpharm.shop/# canadian pharmacy online ship to usa

發佈留言

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