我一直在尝试学习如何使用React进行SSR(不使用Next.js),我已经看到了页面上呈现的HTML,但一旦我将css导入添加到样式中,组件便开始抛出错误(C:\Users\Frozen\Desktop\ssr stuff\ssr4\src\App.css:1 body { ^
语法错误:意外的标记“{”)
.Babel
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './build'),
filename: "bundle.js",
publicPath: "/"
},
devServer: {
port: 3010,
static: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env', "@babel/preset-react"]
}
},
},
{
test: /\.(css|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
publicPath: "/"
})
]
};
server.js
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './src/App.js';
import path from 'path';
import fs from 'fs';
const app = express();
app.get('/', (req, res) => {
console.log('in /');
fs.readFile(
path.resolve('./build/index.html'),
'utf8',
(err, data) => {
if (err) {
console.log(err);
return res.status(500).send('Internal Server Error');
}
const html = data.replace(
'<div id="root"></div>',
`<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
)
console.log(html)
return res.send(html);
}
);
});
app.use(express.static(path.resolve(__dirname,'build')));
app.listen(3000, () => {
console.log('server listening on port 3000')
})
我也不明白为什么我必须把app.use(static)放在app.get('/')下面,而不是中间件应该一个接一个地从上到下(如果我把app.use(static)移到app.get('/')上面,在那里我返回的组件我看不到console.log('in/');
index.js
import React from "react";
import ReactDOM from 'react-dom'
import App from "./App";
const appElement = document.getElementById('root');
ReactDOM.hydrate(<App/>, appElement)
我运行npx webpack npx babel-node server.js,我得到了css错误(如果我删除了css导入,我就不会得到它,但我在组件中没有css)。此外,一旦我更改了一些内容(比如当您使用create-react-app时),是否有办法重建并运行server.js?此外,如果有任何其他关于我在当前设置中可以改进的建议,我将不胜感激。
1条答案
按热度按时间huwehgph1#
安装babel-plugin-css-modules-transform
npm install --save-dev babel-plugin-css-modules-transform
.然后将其包含在.babelrc中。
"plugins": ["css-modules-transform"]