In this tutorial, I will explain how to use grunt in Magento 2.
Before starting the installation, Please rename the existing files package.json.sample
and Gruntfile.js.sample
in your root folder as package.json
and Gruntfile.js
respectively.
Follow the below steps to use grunt in Magento 2 :
Step 1 : Install Node.js
First, we need to install a stable version of Node.js.
sudo apt install nodejs
Check Node.js version : node -v
Step 2 : Install Grunt CLI
Now install the Grunt CLI tool globally by the following command :
npm install -g grunt-cli
Step 3 : Install Node.js dependencies
Install the node.js project dependencies, including Grunt, for your Magento instance. To do this, run the following commands in the command prompt :
cd <magento_directory>
npm install
npm update
Step 4 : Add a theme to Grunt configuration
Add your theme to Grunt configuration.
To do this, in the dev/tools/grunt/configs/themes.js file, add your theme in module.exports as shown below:
Samplelesstheme: {
area: 'frontend',
name: 'V4U/Samplelesstheme',
locale: 'en_US',
files: [
'css/styles-m',
'css/styles-l'
],
dsl: 'less'
}
Ex : Vendor Name is V4U and theme name is Samplelesstheme (Download from here)
Samplelesstheme: {
area: 'frontend',
name: 'V4U/Samplelesstheme',
locale: 'en_US',
files: [
'css/styles-m',
'css/styles-l'
],
dsl: 'less'
}
Step 5: Run Grunt commands
The next step is to run the Grunt commands :
grunt clean: This command removes static files related to your theme in both pub/static and var directories.
grunt clean:
Ex : grunt clean:Samplelesstheme
grunt exec: This one republishes source files symlinks to pub/static/frontend/<Vendor>/<theme>/<locale>
.
grunt exec:
Ex : grunt exec:Samplelesstheme
grunt less: This command compiles all the css file using the symlinks in this location pub/static/frontend/<Vendor>/<theme>/<locale>
.
grunt less:Samplelesstheme
grunt watch: This command is used to start the grunt tool to track the changes done in the main files like .less and re-compiles into CSS files.
Ex : grunt watch
Whenever you change any of source file, grunt watch command will show notification in terminal.
🙂 Happy Coding. Keep Liking & Sharing 💻