[英]React Server Side Rendering with CSS (SASS)
我正在嘗試構建一個同構的 React 應用程序,但現在我只將我的問題限制在服務器端渲染部分。 我想在我的應用程序的服務器端呈現一些 React JS 組件。 我可以使用ReactDomServer.renderToString
方法來做到這一點。 但是我無法獲得 CSS(或我的 SASS/SCSS 文件)來使用這些組件。
對於客戶端,我通常可以只使用 Webpack 和 css-loader/style-loader 之類的東西,當我捆綁 JS 時,組件的樣式就會正確。 但是,我不知道如何在服務器端執行此操作。 這是我在服務器文件上運行ts-node
時遇到的錯誤
body {
^
SyntaxError: Unexpected token '{'
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
...
以下是我的相關文件。
import React from "react";
import "./App.scss"
class App extends React.Component {
override render(): React.ReactNode {
return (<div>THIS IS THE APP START</div>);
}
}
export default App;
$mycolor: red;
body {
color: $mycolor;
}
import express from "express";
import ReactDomServer from "react-dom/server";
import App from "./Components/App";
const app = express()
const port = 3000
app.get('/', (req, res) => {
const html = ReactDomServer.renderToString(<App />);
res.send(html);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
{
"include": ["src/**/*"],
"exclude": ["node_modules"],
"compilerOptions": {
"esModuleInterop": true,
"moduleResolution": "Node16",
"jsx": "react-jsx"
}
}
{
"name": "really",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "ts-node src/server.tsx"
},
"dependencies": {
"@types/node-sass": "^4.11.3",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"express": "^4.18.2",
"node-sass": "^8.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sass": "^1.56.1",
"ts-node": "^10.9.1"
},
"devDependencies": {
"typescript": "^4.9.3"
}
}
不確定是否可以在快遞服務組件之前加載 CSS。 另一種可能的方法是使用 webpack 來捆綁服務器端文件並加載 CSS 但我不知道這是否可行,而且我覺得服務器端部分很奇怪。 有沒有辦法在沒有 webpack 的情況下做到這一點?
在構建期間,您仍然需要將 scss 轉換為 css 文件,css 文件應將 go 放入公共文件夾,然后在 html 反應模板中添加鏈接 rel
<link rel="stylesheet" href="../../public/styles.css">
當瀏覽器調用它時,你需要用 express 來提供它
app.get('/styles.css', (req, res) => {
res.sendFile(__dirname + "/" + "styles.css");
});
或存在該文件的服務器 static 文件夾
app.use(express.static('public'));
使用ts-node
無法執行此操作,因為它沒有導入 css 或 sass 文件的插件(出現錯誤是因為它無法解析 SASS 語法)。 您可以使用 webpack 來完成,它具有導入 sass 文件的插件。
但是,已經有大量 SSR 框架可用,例如Next.js或 Gatsby 可以為您處理所有這些。 使用 Next.js,您還可以動態訪問請求數據並為每個請求呈現不同的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.