Fixes #78 Custom require extension for marko files

This commit is contained in:
Patrick Steele-Idem 2015-05-21 17:16:29 -06:00
parent 91ec007718
commit 391aa80a9a
2 changed files with 64 additions and 1 deletions

View File

@ -51,11 +51,22 @@ exports.enable = function() {
if (!path) {
throw new Error('Invalid path');
}
var templatePath = path;
if (typeof templatePath !== 'string') {
templatePath = path.path;
}
if (typeof templatePath === 'string') {
templatePath = templatePath.replace(/\.js$/, '');
}
var template = oldLoad.apply(runtime, arguments);
// Store the current last modified with the template
template.__hotReloadModifiedFlag = modifiedFlag;
template.__hotReloadPath = path;
template.__hotReloadPath = templatePath;
return template;
};
@ -74,6 +85,7 @@ exports.handleFileModified = function(path) {
console.log('[marko/hot-reload] File modified: ' + path);
if (path.endsWith('.marko') || path.endsWith('.marko.html')) {
delete require.cache[path];
delete require.cache[path + '.js'];
}

51
node-require.js Normal file
View File

@ -0,0 +1,51 @@
var path = require('path');
var resolveFrom = require('resolve-from');
var fs = require('fs');
var fsReadOptions = { encoding: 'utf8' };
function compile(templatePath, markoCompiler, compilerOptions) {
var targetDir = path.dirname(templatePath);
var targetFile = templatePath + '.js';
var compiler = markoCompiler.createCompiler(templatePath, compilerOptions);
var isUpToDate = compiler.checkUpToDate(targetFile);
var compiledSrc;
if (isUpToDate) {
compiledSrc = fs.readFileSync(targetFile, fsReadOptions);
} else {
var templateSrc = fs.readFileSync(templatePath, fsReadOptions);
compiledSrc = compiler.compile(templateSrc);
var filename = path.basename(targetFile);
var tempFile = path.join(targetDir, '.' + process.pid + '.' + Date.now() + '.' + filename);
fs.writeFileSync(tempFile, compiledSrc, fsReadOptions);
fs.renameSync(tempFile, targetFile);
}
return compiledSrc + '\nexports.path=__filename;\nmodule.exports = require("marko").load(exports);';
}
exports.install = function(options) {
options = options || {};
var compilerOptions = options.compilerOptions;
var extension = options.extension || '.marko';
if (extension.charAt(0) !== '.') {
extension = '.' + extension;
}
if (require.extensions[extension]) {
return;
}
require.extensions[extension] = function markoExtension(module, filename) {
var dirname = path.dirname(filename);
var markoCompilerModulePath = resolveFrom(dirname, 'marko/compiler');
var markoCompiler = require(markoCompilerModulePath);
var compiledSrc = compile(filename, markoCompiler, compilerOptions);
module._compile(compiledSrc, filename + '.js');
};
};