diff --git a/hot-reload/index.js b/hot-reload/index.js index 3cdfdac02..f7c724f92 100644 --- a/hot-reload/index.js +++ b/hot-reload/index.js @@ -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']; } diff --git a/node-require.js b/node-require.js new file mode 100644 index 000000000..7a7033e45 --- /dev/null +++ b/node-require.js @@ -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'); + }; +}; \ No newline at end of file