Skip to content

Instantly share code, notes, and snippets.

@chamberlainpi
Last active September 12, 2015 20:37
Show Gist options
  • Save chamberlainpi/90e38deeccc94145b033 to your computer and use it in GitHub Desktop.
Save chamberlainpi/90e38deeccc94145b033 to your computer and use it in GitHub Desktop.
A Merging tool for HTML files that requires all CSS / JS from external sources to be inlined in specific areas of a document.
package;
import haxe.io.Path;
import haxe.Json;
import sys.FileSystem;
import sys.io.File;
/**
* @author: Pierre Chamberlain
* @version: 1.0
*
* Arguments:
*
* - The arguments are INPUT and OUTPUT filepaths to the HTML documents.
* (1st = template, 2nd = output).
*
* HTML Template File Usage:
*
* - Type a multiline comment with a list of files to lookup, like so:
* @MacroMerge: inlined/reset.css, inlined/main.css
* @MacroMerge: public/vendor.js, public/app.js
*
* Brunch Usage:
*
* - To run this macro as a post-build process, you will need "after-brunch".
* You can find the NPM install instructions here:
*
* - Then you can set your brunch config file like so:
*
* afterBrunch: [
* "haxe -cp . --macro MacroMerge.html('inlined/index.html','public/index.html')"
* ]
*
*/
class MacroMerge {
//This is the main method called from the CMD line (or Brunch.io, etc.)
static function html(input:String, output:String) {
trace(input + " : " + FileSystem.exists(input));
var content = File.getContent(input);
var lines = content.split("\n");
var results:Array<String> = [];
for (line in lines) {
if (line.indexOf("@MacroMerge:")>-1) {
inspectLine(results, line);
continue;
}
results.push( line );
}
var outputAbs = FileSystem.absolutePath(output);
File.saveContent(outputAbs, results.join("\n") );
trace("Files merged to HTML file: " + output);
}
static function inspectLine(results:Array<String>, line:String) {
line = StringTools.trim(line);
line = StringTools.replace(line, "*/", "");
line = StringTools.replace(line, "-->", "");
var files = line.split(":")[1].split(",");
var merged:Array<String> = [];
for (file in files) {
file = StringTools.trim(file);
var subContent = File.getContent(file);
merged.push( subContent );
}
results.push( merged.join("\n") );
}
}
@chamberlainpi
Copy link
Author

For those of you who use Brunch.io with the auto-reload plugin, make sure to add a bit of delay in your configuration file.

autoReload:
    delay: 600

This amount seems fine for my particular use-case, but you may want to tweak it depending on the size of your project to give a chance for this Haxe Macro to write to the FileSystem and have your browser auto-refresh only once it's completed.

@chamberlainpi
Copy link
Author

Note: This also works great with Brunch.io's UglifyJS plugin to squeeze down the filesize of the final HTML file even further.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment