How does Atom manage to load ".less" files seamlessly?


Hi all! I am wondering what method does Atom use to load .less files seamlessly… Let me explain: when I edit my styles.less and save it, it (almost) immediately loads into Atom. How am I supposed to achieve such a behavior with the html files in my atom-shell app? Is there a script like ‘coffee-script/register’ I can use to load less/sass/stylus files in my html pages? Thanks :smile:

EDIT: I found that lesscss provides a way of including less files directly in the header using a js script:
This seems very tied to lesscss and cannot be used for other preprocessors… Is there a way to provide this without having to precompile files?


You can inject styles and scripts into the DOM at any time. You can do this directly from node or in the web page, using JS either way.


So the basic way is to load the sourcefiles, render them and then injecting the results in the page?


I don’t know anything about rendering CSS but I would assume you just run some NPM module that does the compiling.


Yeah but normally you’d use that for precompiling the files, and then running the app. I want to be able to compile the files on the fly while running the app. I’ll try to do it and then report :smile:


I wrote this script to allow automatic loading of Stylus files:

stylus = require 'stylus'
_ = require 'underscore'
fs = require 'fs'

exports.loadStylesheet = (document) ->
  head = document.getElementsByTagName('head')[0]
  styles = head.getElementsByTagName('link')
  # We are searching for something like
  # <link rel="stylesheet/stylus" href="myfile.styl">
  _.each styles, (element, index, list) ->
    rel = element.getAttribute 'rel'
    if rel == 'stylesheet/stylus'
       href = element.getAttribute 'href'
      # This could have been done with ajax, I know,
      # but it would have been a huge mess of callbacks
      source = fs.readFileSync __dirname + '/../' + href, 'utf8'
      stylus(source).render (err, css) ->
        styleNode = document.createElement 'style'
        styleNode.setAttribute 'type', 'text/css'
        styleNode.appendChild document.createTextNode(css)
        head.appendChild styleNode
        # Done.

It is to be used like this:
in html file:

   <link rel="stylesheet/stylus" href="myfile">
    var stylusLoader = require('stylusLoader.js');
    window.onload = function() { stylusLoader.loadStylesheet(document); }

Hope this is helpful to someone :smiley:


@frabert So, basically that is how you loaded the stylus files dynamically, right? I wonder if this could be used on a webpage as well. Without the node - electron involved.

Thanks for sharing.


Yes, it is actually pretty easy. There are a lot of js modules to do this. I wrote my own by checking the version of a CSS file using HEAD requests. When the file changes I just load the new CSS.