Use Grunt to compile less files in real time

Below is the file organization of the project

  • Generate package.json file with the NPM init command.

  • Install Devdependencies/denpendencies you need.

    • npm install grunt –save-dev

    • npm install load-grunt-tasks –save-dev

    • npm install time-grunt –save-dev

    • npm install grunt-contrib-watch –save-dev

    • npm install grunt-contrib-less –save-dev

    • npm install grunt –save

GruntFile. Js configuration

    'use strict';
    
    module.exports = function(grunt){
        require('time-grunt')(grunt);
        require('load-grunt-tasks')(grunt);
        
        grunt.initConfig({
            less: {
                build: {
                    expand: true,
                    cwd: 'less/',
                    src: '['*.less']',
                    dist: 'css/',
                    ext: '.css'
                }
            },
            
            watch: {
                files: ['less/**/*.less'],
                tasks: ['default']
            }
        });
        
        grunt.registerTask('default', ['less']);
    }
  • Grunt.initConfig () passes in an object

  • Each field name represents a task

  • The contents of the task are the target

  • In the less task:

    • Expand: true to start dynamic compilation

    • CWD: ‘less/’ All files specified in ‘SRC’ are relative to the path specified by this property

    • SRC: [‘*.less’] matches all less files relative to the files in the CWD path

    • Dest: ‘CSS /’ The path to the generated object file

    • Ext: ‘.css’ replaces the suffix of all generated object files with this property

  • In the watch task:

    • Files :[‘less/**/*.less’] = listen to all less files in less folder, and all less files in all directories

    • Tasks: [‘default’] indicates that the task will be executed if a change is made to the file being monitored above

  • Grunt.registerTask (‘default’, [‘less’]) // Register ‘default’ with ‘less’ tasks

Introducing less files into the HTML files

<link href='less/index.less'/>
<script src='node_modules/less/less.js'></script>

Initiate the Grunt mission

Open a command line window and type Grunt Watch

This command starts Grunt’s task(watch) because tasks are configured inside the task(watch), which means that the default task will be executed if the file being monitored changes

The changes you make in the index.less file will be compiled to CSS on the command line in real time, so you can refresh your browser

Use the compiler features that come with the editor

WebStorm has its own less/sass compilation function, you can also carry out the corresponding configuration for real-time compilation of less files