How do I parse JSX

We know that a React component is JSX that is parsed into a normal JS object via Babel. We need the following kit

  • @babel/core
  • @babel/node
  • @babel/preset-env
  • @babel/preset-react

Achieve one small goal

ReactDOMServer. RenderToString in nodejs environment rendering the HTML string.

The installation

cd your_target_project_dir

yarn init -y

yarn add react react-dom

yarn add @babel/core @babel/node @babel/preset-env @babel/react
Copy the code

Configure the Babel

{
  "presets": ["@babel/preset-env"."@babel/preset-react"]}Copy the code

Configuring the Startup Script

"scripts": {
   "dev": "babel-node ./src/index.js"
},
Copy the code

Note that we use babel-node instead of the node script.

Set the main entry file SRC /index.js

import React from 'react'
import ReactDOMServer from 'react-dom/server'
import App from './App.jsx'

const html = ReactDOMServer.renderToString(<App />)
console.log(html)
Copy the code

Write a React component

import React from "react";

const App = () = > {
  return <div>123</div>;
};

export default App;
Copy the code

Join the Express framework and write a simple interface to get HTML

// const App = require('./App.jsx').default
// const React = require('react')
// const ReactDOMServer = require('react-dom/server')
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import express from 'express'
import App from './App.jsx'

const app = express()

app.use('/'.async function (req, res) {
  const html = await ReactDOMServer.renderToString(<App />)
  res.send(html)
})

app.listen(1000.async function (req, res) {
  console.log('listen... ')})Copy the code

Open http://localhost:1000/ in your browser and get 123 on the page. Such a static component is rendered to the browser.

The problem

This is a static component without any dynamic interaction. No data is loaded. And there are no apis in nodeJS for Windows, Documents, etc. So there are a lot of other things to be aware of. These issues will be discussed in the following articles, and the theoretical basis of Nodejs isomorphism React will be supplemented in the following articles.