less/LessUnit.js

/**
 * @module flitter-less/LessUnit
 */

const Unit = require('libflitter/Unit')
const path = require('path')

/**
 * Provides a JIT compiler for Less styles.
 * Serves them at /style-asset from the specified asset folder.
 * 
 * @extends module:libflitter/Unit~Unit
 */
class LessUnit extends Unit {
    /**
     * Defines the services required by this unit.
     * @returns {Array<string>}
     */
    static get services() {
        return [...super.services, 'configs']
    }

    /**
     * Get the name of the service provided by this unit: 'less'
     * @returns {string} - 'less'
     */
    static get name() {
        return 'less'
    }
    
    /**
     * Initialize the class and get the Less file dir.
     * @param {string} style_path - Path to the *.less files to be served.
     */
    constructor( style_path = './app/assets/less' ){
        super()
        this.directory = path.resolve(style_path)
    }
    
    /**
     * Initialize the unit.
     * Registers the Less compiler with the underlying Express app.
     * @param {module:libflitter/app/FlitterApp~FlitterApp} app
     * @returns {Promise<void>}
     */
    async go(app){
        this.less_compiler = require('express-less')
        const config = this.configs.guarantee('server.less', {
            access_route: '/style-asset',
        })
        this.access_route = config.access_route
        app.express.use(this.access_route, this.less_compiler(path.resolve(this.directory)))
    }
}

module.exports = exports = LessUnit