Last active
January 12, 2021 01:44
-
-
Save Orbis25/f8f8cdda9fc4f5511437d0b7cc96b360 to your computer and use it in GitHub Desktop.
server side rendering in reactjs with typescript
This file contains 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
Show hidden characters
{ | |
"plugins": [ | |
"@babel/plugin-proposal-class-properties", | |
"@babel/plugin-syntax-dynamic-import", | |
"@babel/plugin-proposal-optional-chaining", | |
"@babel/plugin-proposal-nullish-coalescing-operator" | |
], | |
"presets": ["@babel/preset-react"] | |
} |
This file contains 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
require("core-js/stable"); | |
require("regenerator-runtime/runtime") | |
require("ignore-styles"); | |
require("@babel/register")({ | |
ignore: [/(node_module)/], | |
presets: [ | |
"@babel/preset-env", | |
"@babel/preset-react", | |
"@babel/preset-typescript", | |
], | |
extensions: [".js", ".jsx", ".ts", ".tsx"], | |
plugins: [ | |
"@babel/plugin-proposal-class-properties", | |
"@babel/plugin-syntax-dynamic-import", | |
"@babel/plugin-proposal-optional-chaining", | |
"@babel/plugin-proposal-nullish-coalescing-operator" | |
], | |
}); | |
// server configuration | |
require("./server.tsx"); |
This file contains 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
import React from "react"; | |
import fs from "fs"; | |
import express from "express"; | |
import ReactDOMServer from "react-dom/server"; | |
import App from "../src/App.tsx"; | |
import path from "path"; | |
const PORT = 8080; | |
const app = express(); | |
app.use("^/$", (req, res, next) => { | |
const content = ReactDOMServer.renderToNodeStream(<App />) | |
fs.readFile(path.resolve("./build/index.html"), "utf-8", (err, data) => { | |
if (err) { | |
console.log(err); | |
return res.status(500).send("Some error happened"); | |
} | |
return res.send( | |
data.replace( | |
"<div id='root'></div>", | |
`<div id='root'>${content}</div>` | |
) | |
); | |
}); | |
}); | |
app.use(express.static(path.resolve(__dirname, "..", "build"))); | |
app.listen(PORT, () => { | |
console.log(`APP LAUNCHED ON PORT ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment