Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP V8Js render react written in typescript

Tags:

php

reactjs

I've been writing react components with typescript, following the instructions in official typescript docs:

https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

I am using V8Js php extension to render React on server side, but it seems I lack the understanding of what is the correct way using V8Js.

this is my react application: (client-side rendered)

http://codepen.io/MasterScripter/pen/xqRZQO

I tried to render on side-server:

<?php

$v8 = new V8Js();

$react = [];

// stubs, react
$react[] = "var console = {warn: function(){}, error: print}";
$react[] = "var global = {}";
$react[] = file_get_contents('./dist/react.js');
$react[] = "var React = global.React";

$react[] = file_get_contents('./dist/bundle.js');
$data = [
  'value' => 1,
  'onClick' => 'function'
];
$react[] = sprintf(
  "React.renderComponentToString(Square({data: %s}), print)",
  json_encode($data));
$react = implode(";", $react);

try {
  $v8->executeString($react);
} catch(V8JsException $e) {
  echo "
    File: {$e->getJsFileName()} \n
    Line Number: {$e->getJsLineNumber()} \n
    Source Line: {$e->getJsSourceLine()} \n
    Trace: {$e->getJsTrace()}
  ";
}

'react.js' includes raw react & react-dom code, 'bundle.js' includes webpack bundle, same as the one from the pen above.

I get this error:

File: V8Js::compileString() 

Line Number: 209 

Source Line: module.exports = ReactDOM; 

Trace: ReferenceError: ReactDOM is not defined
at Object.setPrototypeOf.__proto__ (V8Js::compileString():209:18)
at __webpack_require__ (V8Js::compileString():47:30)
at Object.<anonymous> (V8Js::compileString():300:16)
at __webpack_require__ (V8Js::compileString():47:30)
at module.exports (V8Js::compileString():93:18)
at V8Js::compileString():96:10

any suggestions / hints how I can do this properly?

like image 256
Yonatan Naxon Avatar asked Mar 07 '17 13:03

Yonatan Naxon


1 Answers

Looks like you need to add

$react[] = "var React = global.React, ReactDOM = global.ReactDOM, ReactDOMServer = global.ReactDOMServer;";

instead of

$react[] = "var React = global.React";

(I haven't tested it; just based on this. I don't have much experience with V8JS either. I recommend reading this for a nice introduction.)

like image 180
alepeino Avatar answered Nov 14 '22 02:11

alepeino