React常用知识

create-react-app搭建React项目,mobx管理

2019-02-02  本文已影响195人  刀刀小技

1、安装新建

npm install create-react-app -g
create-react-app myapp
cd myapp
启动:
npm start

创建的项目名称不能包含大写字母,否则会报错
* name can no longer contain capital letters

2、Route路由配置

npm install react-router-dom --save

在src目录下新建router.js

import React from 'react'
import {
    BrowserRouter as Router,
    Route
} from 'react-router-dom'
import Home from './views/Home'

const RootRouter = () =>(
    <Router>
        <div>
            <Route exact path="/" component={Home} />
        </div>
    </Router>
)
export default RootRouter

ps: 若添加多个路由配置,需在<Router></Router>里面添加div进行包裹,否则会报错
A <Router> may have only one child element

打开index.js文件,修改

import React from 'react';
import ReactDOM from 'react-dom'
import * as serviceWorker from './serviceWorker';

import RootRouter from './router.js'

ReactDOM.render(<RootRouter />, document.getElementById('root'));
serviceWorker.unregister();

3、配置mobx

1、安装mobx:
npm install mobx mobx-react --save

2、新增store.js

import { observable, action, computed } from "mobx";
class Store {
    //do something
}
export default Store;

3、修改index.js文件

import { Provider } from 'mobx-react'
import Store from './store'
const store = new Store();
ReactDOM.render(
    <Provider store={store}>
        <RootRouter />
    </Provider>
    , document.getElementById('root'));

4、增加less预处理器

1、使用eject 暴露出webpack配置文件,手动修改
npm run eject
2、使用react-app-rewired
3、替换react-scripts包

#自定义 scripts 包方式 
#一个已经发布到 npm 仓库上的包的名字,比如your-scripts,里面包含了修改过的 webpack 配置
$ create-react-app foo --scripts-version 自定义包

1)、使用react-app-rewired
npm i --save-dev react-app-rewired

在项目根目录下创建config-overrides.js文件

module.exports = function override(config, env) {
  //do stuff with the webpack config...
  return config;
}

修改package.json文件的启动配置
"start": "react-app-rewired start"
2)、配置less使用
npm install --save-dev react-app-rewire-less

修改config-overrides.js文件

const rewireLess = require('react-app-rewire-less');
module.exports = function override(config, env) {
  config = rewireLess(config, env);
  return config;
}

5、常见问题

1、安装react-router-dom后,启动'npm start'会报错 react-scripts 不是内部或外部命令,也不是可运行的程序

2、安装使用mobx后报错 Support for the experimental syntax 'decorators-legacy' isn't currently enabled (3:5):

const rewireMobX = require("react-app-rewire-mobx");
module.exports = function override(config, env) {
  config = rewireMobX(config, env);

  return config;
};

3、报错
The 'decorators' plugin requires a 'decoratorsBeforeExport' option, whose value must be a boolean. If you are migrating from Babylon/Babel 6 or want to use the old decorators proposal, you should use the 'decorators-legacy' plugin instead of 'decorators'.

上一篇下一篇

猜你喜欢

热点阅读