Skip to content

Instantly share code, notes, and snippets.

@webuniverseio
Created January 24, 2017 00:02
Show Gist options
  • Save webuniverseio/633684f6050cb5449056f22db8c01aa5 to your computer and use it in GitHub Desktop.
Save webuniverseio/633684f6050cb5449056f22db8c01aa5 to your computer and use it in GitHub Desktop.
Boilerplate for adding another folder to express-react-views engine.

With express-react-views adding another folder to jsx engine in such a way that files are not cached in development mode is crazy at the moment :(. If you're on windows it might be even worse because of path differences... So enjoy :)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jsx');
const additionalJSXFolders = [path.join(__dirname, 'static/src/js')];

const getWindowsCompatiblePathRegExp = x =>
	minimatch.makeRe(x, {nocase: true}).source.slice(1, -1);
const pathsToRegex = mapper => paths =>
	Right(paths)
	.map(paths => paths.map(mapper))
	.map(x => `(${x.join('|')})`)
	.map(x => new RegExp(x, 'i'))
	.get();

const renderJsx = require('express-react-views').createEngine({
	babel: {
		only: pathsToRegex(getWindowsCompatiblePathRegExp)(
			[app.locals.settings.views].concat(additionalJSXFolders)),
		presets: [
			'react',
			'es2015',
		],
	}
});
app.engine('jsx', function(...args) {
	const result = renderJsx.apply(this, args);
	if (app.locals.settings.env === 'development') {
		// Remove all files from the module cache that are in the view folder.
		Object.keys(require.cache).forEach(function(module) {
			if (pathsToRegex(_.escapeRegExp)(additionalJSXFolders).test(require.cache[module].filename)) {
				delete require.cache[module];
			}
		});
	}
	return result;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment