Created
February 27, 2018 10:16
-
-
Save geowarin/2d41ca8102df8dd0b4f72253e0722271 to your computer and use it in GitHub Desktop.
SSR with J2V8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getHtml(componentPath: String, modelJson: String, currentUrl: String): String { | |
val nodeJS = NodeJS.createNodeJS() | |
nodeJS.runtime.add("componentPath", componentPath) | |
nodeJS.runtime.add("modelJson", modelJson) | |
nodeJS.runtime.add("currentUrl", currentUrl) | |
try { | |
val vendors = nodeJS.require(File(bundleLocation, "vendor.js")) | |
val mainModule = nodeJS.require(File(bundleLocation, "pages.js")) | |
val exports = nodeJS.require(File(bundleLocation, "renderer.js")) | |
while (nodeJS.isRunning) { | |
nodeJS.handleMessage() | |
} | |
val fb = exports.get("FuseBox") as V8Function | |
val import = fb.get("import") as V8Function | |
val args = V8Array(nodeJS.runtime) | |
args.push("default/core/renderer.js") | |
val html = import.call(null, args) as String | |
vendors.release() | |
mainModule.release() | |
fb.release() | |
import.release() | |
args.release() | |
exports.release() | |
nodeJS.release() | |
return html | |
} catch (e: V8ScriptExecutionException) { | |
e.printStackTrace() | |
return "" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const React = require("react"); | |
const ReactServer = require("react-dom/server"); | |
const loaded = FuseBox.import(componentPath); | |
if (!loaded) { | |
throw new Error(`Could not find component ${componentPath}`) | |
} | |
const Component = loaded.default; | |
const model = JSON.parse(modelJson); | |
global.currentUrl = currentUrl; | |
const Root = React.createElement(Component, {model}); | |
let html = ReactServer.renderToString(Root); | |
module.exports = html; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment