How to Use Grunt in Magento 2
Learn how to use Grunt in Magento 2 for frontend development, including compiling LESS, watching files, and improving workflow.
Overview
Grunt is a JavaScript task runner used in Magento 2 to automate frontend tasks like compiling LESS to CSS, minification, and live file watching during development.
Prerequisites
- Node.js and npm installed
- Magento 2 project setup
- Access to Magento root directory
Step-by-Step Setup
- Install Grunt CLI globally.
- Install project dependencies.
- Configure Grunt for your theme.
- Run Grunt commands.
Step 1: Install Grunt CLI
npm install -g grunt-cli
Step 2: Install Dependencies
cd <magento-root>
npm install
Step 3: Configure Grunt
Edit grunt-config.json file:
{
"themes": {
"frontend/Vendor/childtheme": {
"area": "frontend",
"name": "Vendor/childtheme",
"locale": "en_US",
"files": [
"css/styles-m",
"css/styles-l"
],
"dsl": "less"
}
}
}
Step 4: Run Grunt Commands
-
Clean:
grunt clean -
Compile LESS:
grunt exec:<theme> -
Watch Files (Auto Compile):
grunt watch
Common Commands
grunt setup– Initial setupgrunt exec– Compile static filesgrunt watch– Watch file changesgrunt less– Compile LESS only
Important Notes
- Use Grunt only in developer mode.
- Ensure correct theme path in
grunt-config.json. - Clear cache if changes are not visible.
- Grunt improves frontend workflow significantly.