Skip to content

Instantly share code, notes, and snippets.

@tonyonodi
Created February 15, 2019 14:51
Show Gist options
  • Save tonyonodi/4ae77821848cb20b037f0eb71a8f7a86 to your computer and use it in GitHub Desktop.
Save tonyonodi/4ae77821848cb20b037f0eb71a8f7a86 to your computer and use it in GitHub Desktop.
Simple build script to compile, minify and inline javascript and css
const fs = require("fs");
const path = require("path");
const cheerio = require("cheerio");
const UglifyJS = require("uglify-js");
const babel = require("@babel/core");
const CleanCSS = require("clean-css");
const htmlMinify = require("html-minifier").minify;
const inputFileName = "index.html";
const babelOptions = {
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "entry",
},
],
],
};
const cleanCSSOptions = {};
const htmlMinifyOptions = {
collapseWhitespace: true,
};
const SRC_DIR = path.join(__dirname, `/../src`);
const BUILD_DIR = path.join(__dirname, `/../build`);
const inputFilePath = path.join(SRC_DIR, inputFileName);
const html = fs.readFileSync(inputFilePath);
const $ = cheerio.load(html);
$("script").replaceWith((_i, rawEl) => {
const el = $(rawEl);
const src = el.attr("src");
const filePath = path.join(SRC_DIR, src);
const code = fs.readFileSync(filePath).toString();
const transformedCode = babel.transformSync(code, babelOptions).code;
const minifiedCode = UglifyJS.minify(transformedCode);
if (minifiedCode.error) {
throw minifiedCode.error;
}
return `<script>${minifiedCode.code}</script>`;
});
$(`link[rel="stylesheet"]`).replaceWith((_i, rawEl) => {
const el = $(rawEl);
const href = el.attr("href");
const filePath = path.join(SRC_DIR, href);
const code = fs.readFileSync(filePath).toString();
const minifiedCode = new CleanCSS(cleanCSSOptions).minify(code).styles;
return `<style>${minifiedCode}</style>`;
});
const minifiedHTML = htmlMinify($.html(), htmlMinifyOptions);
fs.writeFileSync(path.join(BUILD_DIR, inputFileName), minifiedHTML);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment