Skip to content

Instantly share code, notes, and snippets.

@laobubu
Last active March 19, 2020 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laobubu/8d1b09a30d2756e574de to your computer and use it in GitHub Desktop.
Save laobubu/8d1b09a30d2756e574de to your computer and use it in GitHub Desktop.
A Enhanced lite-server tool with sass watching
/**
Enhanced lite-server tool with sass watching.
## What it does
0. run `lite-server`
1. watch `scss/*.scss` and compile into `style/*.css`
## How to use
0. `npm install -g lite-server node-sass`
1. `npm link node-sass` or `npm install sass.js`
2. execute this script.
*/
'use strict';
var child_process = require('child_process');
var fs = require('fs');
var isWindows = /^win/.test(process.platform);
var liteServer = child_process.spawn(isWindows ? 'lite-server.cmd' : 'lite-server');
liteServer.stdout.pipe(process.stdout);
var sassCompile = (function () {
try {
var sassJs = require('sass.js');
return scssStr =>
new Promise(resolve => {
sassJs.compile(scssStr, result => resolve(result.text))
})
} catch (err) {}
try {
var nodeSass = require('node-sass');
return scssStr =>
new Promise(resolve => {
nodeSass.render({
data: scssStr
}, (err, result) => {
if (err) {
console.log(err);
} else
resolve(result.css)
})
})
} catch (err) {}
throw 'Cannot find sass compiler!';
})();
function watchSass(src, dst) {
function nextTrig() {
console.log('[SASS] Compile ' + src);
fs.readFile(src, 'utf-8', (err, srcData) => {
sassCompile(srcData).then(css => {
console.log('[SASS] Finished ' + src);
fs.writeFileSync(dst, css);
})
})
}
fs.watchFile(src, nextTrig);
nextTrig();
}
fs.readdir('scss', (err, names) => {
var tailTest = /\.s[ca]ss$/i;
names.filter(name => tailTest.test(name))
.forEach(name => {
watchSass('scss/' + name, 'style/' + name.replace(tailTest, '.css'))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment