如何通过Material-UI和React-Router服务React应用

时间:2018-11-15 10:41:49

标签: javascript reactjs react-router material-ui

我用这个主要组件React + Material-UI + react-router开发了一个应用程序。这是我完整的package.json

{
  "name": "trader-ui",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^3.2.0",
    "@material-ui/icons": "^3.0.1",
    "@stomp/stompjs": "^5.0.0",
    "axios": "^0.18.0",
    "classnames": "^2.2.6",
    "prop-types": "^15.6.2",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.0.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "proxy": "http://localhost:8080"
}

它在开发服务器上工作正常:

$ npm start

这里是:

enter image description here

但是,当我尝试提供产品版本时:

$ npm run build
$ npm install -g serve
$ serve -s build

外观:

enter image description here

有人可以告诉我生产版本出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

感谢@giorgim的建议。没错使用Material-UI常见问题解决此问题:

  

https://material-ui.com/getting-started/faq/#why-aren--39-t-my-components-rendering-correctly-in-production-builds-

我的样式设置代码位于withRoot.js中:

import React from 'react';
import {createMuiTheme, MuiThemeProvider} from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';

const theme = createMuiTheme({
    typography: {
        useNextVariants: true,
    },
});

function withRoot(Component) {
  function WithRoot(props) {
    return (
      <MuiThemeProvider theme={theme}>
        <CssBaseline />
        <Component {...props} />
      </MuiThemeProvider>
    );
  }

  return WithRoot;
}

export default withRoot;

我只是用JssProvider包装了组件:

import React from 'react';
import { create } from 'jss';
import JssProvider from 'react-jss/lib/JssProvider';
import {
    MuiThemeProvider,
    createMuiTheme,
    createGenerateClassName,
    jssPreset,
} from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';

const theme = createMuiTheme({
    typography: {
        useNextVariants: true,
    },
});

const jss = create(jssPreset());
const generateClassName = createGenerateClassName();

function withRoot(Component) {
  function WithRoot(props) {
    return (
        <JssProvider jss={jss} generateClassName={generateClassName}>
            <MuiThemeProvider theme={theme}>
                <CssBaseline />
                <Component {...props} />
            </MuiThemeProvider>
        </JssProvider>
    );
  }

  return WithRoot;
}

export default withRoot;

当然您应该预先安装react-jss

$ npm install react-jss