diff --git a/lib/compile-sass.js b/lib/compile-sass.js new file mode 100644 index 00000000..80d44ff8 --- /dev/null +++ b/lib/compile-sass.js @@ -0,0 +1,24 @@ +const sass = require("sass"); +const fs = require("fs"); + +const compileSass = () => { + const sassFilenames = fs.readdirSync("./styles"); + + for (const filename of sassFilenames) { + const cssFilename = filename.replace(".scss", ".css"); + + try { + const rendered = sass.renderSync({ + file: `./styles/${filename}`, + debug: true, + outputStyle: "expanded", + }); + + fs.writeFileSync(`./public/styles/${cssFilename}`, rendered.css.toString()); + } catch (err) { + console.log(`\n 🙈🚨 UNABLE TO GENERATE CSS FROM SASS FILE: ${filename} 🚨🙈 \n ERROR: ${err} \n`); + } + } +}; + +module.exports = compileSass; diff --git a/lib/sass-middleware.js b/lib/sass-middleware.js deleted file mode 100644 index ab629f4b..00000000 --- a/lib/sass-middleware.js +++ /dev/null @@ -1,26 +0,0 @@ -const sass = require('sass') -const fs = require('fs') - -const sassMiddleware = (options) => { - return (req, res, next) => { - const cssFilename = req.path.replace(/\.[^/.]+$/, '') - const { source, destination, isSass } = options - const extension = isSass ? 'sass' : 'scss' - - try { - const rendered = sass.renderSync({ - file: `${source}${cssFilename}.${extension}`, - outFile: `${destination}${cssFilename}.css`, - debug: true, - outputStyle: 'expanded' - }) - fs.writeFileSync(`${destination}${cssFilename}.css`, rendered.css.toString()) - } catch (e) { - console.log(`\n 🙈🚨 UNABLE TO GENERATE CSS FROM SASS FILE: ${cssFilename.substring(1)}.${extension} 🚨🙈 \n - ERROR: ${e} \n`) - } - - next() - } -} -module.exports = sassMiddleware \ No newline at end of file diff --git a/nodemon.json b/nodemon.json new file mode 100644 index 00000000..0e95927d --- /dev/null +++ b/nodemon.json @@ -0,0 +1,3 @@ +{ + "ext": "html,css,js,scss,ejs" +} diff --git a/server.js b/server.js index e2067545..98cff08c 100644 --- a/server.js +++ b/server.js @@ -1,8 +1,10 @@ // load .env data into process.env require('dotenv').config(); +// compile SCSS files on server start/restart +require('./lib/compile-sass')(); + // Web server config -const sassMiddleware = require('./lib/sass-middleware'); const express = require('express'); const morgan = require('morgan'); @@ -16,14 +18,6 @@ app.set('view engine', 'ejs'); // The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes. app.use(morgan('dev')); app.use(express.urlencoded({ extended: true })); -app.use( - '/styles', - sassMiddleware({ - source: __dirname + '/styles', - destination: __dirname + '/public/styles', - isSass: false, // false => scss, true => sass - }) -); app.use(express.static('public')); // Separated Routes for each Resource