我正在编写一个使用服务器端渲染的React应用。我正在按照instruction设置文件。
这是我的.babelrc
配置文件
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": { "version": 3, "proposals": true },
"targets": {
"browsers": "> 1%, not ie 11, not op_mini all",
"node": 13
}
}
],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-runtime",
[
"import",
{
"libraryName": "@material-ui/icons",
"libraryDirectory": "utils", // default: lib
"camel2DashComponentName": false // default: true
},
"@material-ui/icons"
]
]
}
这是webpack.config.js
文件
const path = require("path");
const nodeExternals = require("webpack-node-externals");
const commonConfig = {
devtool: "source-map",
module: {
rules: [{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }]
},
resolve: {
alias: {
"@material-ui/core": "@material-ui/core/es"
}
}
};
module.exports = [
{
...commonConfig,
entry: "./src/client",
output: {
path: path.resolve(__dirname, "public")
}
},
{
...commonConfig,
target: "node",
entry: "./src/server",
output: {
path: path.resolve(__dirname, "server")
},
externals: [nodeExternals()]
}
];
(这里是CodeSandBox中的完整code,如果您想尝试,这里是Github中的内容)
出现的问题是当我捆绑文件时,在开发模式下,一切正常。但是当我尝试生产模式时,CSS部分开始表现异常。首次从localhost
加载文件时,文件的样式正确(这种情况会在很短的时间内发生),然后由于缺少某些样式而导致样式错误。
当我尝试调查时,发现所有缺少的样式都是我用makeStyles()
编写的部分。所有内置样式都可以正常工作。
我尝试删除此post之后的resolve
中的所有webpack.config.js
属性,但是它不起作用。无论我尝试更改该属性如何,都不会发生。
因此,现在我发现可以使应用程序在生产版本中正常运行的唯一方法是删除删除样式文件的代码(您可以在client.js
文件的末尾找到该部分),但是我我不确定这样做的结果是什么。
所以我的问题是:
为什么在开发和生产两种模式之间有如此大的差异?我知道生产模式将包括一些缩小,摇树等,并且开发中除了缩小以外,大部分都是开发模式。那为什么有区别呢?
编辑:我发现了此错误的两个可能且可行的修复程序:一个是停止删除这些CSS文件(我在client.js
文件中编写的代码);另一个是删除nodeExternal()
中的webpack.config.js
插件,并将所有内容捆绑到服务器文件中。您如何看待?
答案 0 :(得分:4)
我有一个类似的问题,尽管没有服务器端呈现。这是由于在开发和生产环境中样式表的顺序不同引起的,导致了不必要的覆盖。在开发环境中,由makeStyles()
创建的所有样式表都在所有MUI样式表之后注入,但在生产中它们是混合的。
解决方案:
为所有{ index: 1 }
调用添加一个选项:makeStyles()
,以便将那些工作表放置在索引为0(默认情况下)的MUI工作表之后。此可选参数直接传递给基础JSS的jss.createStyleSheet()
,并指定注入顺序:
const useStyles = makeStyles(
(...), // styles
{ index: 1 }, // optional argument for JSS, to set position after MUI stylesheets
)