Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const ts = require('typescript');
- const crypto = require('crypto');
- const scriptCache = {};
- module.exports = function() {
- let originalCompiler = null;
- const tsCompiler = (script, cb) => {
- const hash = crypto
- .createHash('md5')
- .update(script)
- .digest('hex');
- if (!scriptCache[hash]) {
- script = ts.transpileModule(script, {
- compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES5 }
- }).outputText;
- console.log(`Compiled code with has ${hash} to: \n${script}`);
- originalCompiler(script, cb);
- scriptCache[hash] = script;
- } else {
- console.log('Using ts cache');
- originalCompiler(scriptCache[hash], cb);
- }
- };
- return function(req, res, next) {
- console.log('I have middleware');
- const { compiler } = req.webtaskContext;
- if (originalCompiler === null && compiler.nodejsCompiler) {
- originalCompiler = compiler.nodejsCompiler;
- }
- compiler.nodejsCompiler = tsCompiler;
- return next();
- };
- };
Add Comment
Please, Sign In to add comment