Set up static view rendering

This commit is contained in:
Ray Schamp 2016-04-12 08:23:43 -04:00
parent 0ee2234c08
commit 3bdb95d40d
3 changed files with 52 additions and 12 deletions

View file

@ -1,22 +1,12 @@
var crypto = require('crypto'); var crypto = require('crypto');
var defaults = require('lodash.defaults');
var fs = require('fs');
var mustache = require('mustache');
var path = require('path');
var config = require('./config'); var render = require('./render.js');
/** /**
* Constructor * Constructor
*/ */
function Handler (route) { function Handler (route) {
// Route definition var output = render(route);
defaults(route, config);
// Render template
var location = path.resolve(__dirname, './template.html');
var template = fs.readFileSync(location, 'utf8');
var output = mustache.render(template, route);
var checksum = crypto.createHash('md5').update(output).digest('hex'); var checksum = crypto.createHash('md5').update(output).digest('hex');
return function (req, res) { return function (req, res) {

16
server/render.js Normal file
View file

@ -0,0 +1,16 @@
var defaults = require('lodash.defaults');
var fs = require('fs');
var mustache = require('mustache');
var path = require('path');
var config = require('./config');
module.exports = function (route) {
// Route definition
defaults(route, config);
// Render template
var location = path.resolve(__dirname, './template.html');
var template = fs.readFileSync(location, 'utf8');
return mustache.render(template, route);
};

View file

@ -5,6 +5,36 @@ var webpack = require('webpack');
var routes = require('./server/routes.json'); var routes = require('./server/routes.json');
function HtmlGeneratorPlugin (options) {
this.options = options;
return this;
}
HtmlGeneratorPlugin.prototype.apply = function (compiler) {
var render = this.options.render;
var routes = this.options.routes;
compiler.plugin('emit', function (compilation, callback) {
var outputRoutes = {};
routes.forEach(function (route) {
var filename = route.view + '.html';
var content = render(route);
outputRoutes[route.pattern] = filename;
compilation.assets[filename] = {
source: function () {return content;},
size: function () {return content.length;}
};
});
var routeJson = JSON.stringify(outputRoutes);
compilation.assets['routes.json'] = {
source: function () {return routeJson;},
size: function () {return routeJson.length;}
};
callback();
});
};
// Prepare all entry points // Prepare all entry points
var entry = { var entry = {
init: './src/init.js' init: './src/init.js'
@ -56,6 +86,10 @@ module.exports = {
fs: 'empty' fs: 'empty'
}, },
plugins: [ plugins: [
new HtmlGeneratorPlugin({
render: require('./server/render.js'),
routes: routes
}),
new CopyWebpackPlugin([ new CopyWebpackPlugin([
{from: 'static'}, {from: 'static'},
{from: 'intl', to: 'js'} {from: 'intl', to: 'js'}