react-mobx-less-router架构起手

使用create-react-app创建项目

创建项目

create-react-app project

抛出配置文件

npm run eject

mobx

安装mobx

npm install mobx mobx-react –save

mobx中文文档

启用装饰器语法

在MobX 中使用 ES.next 装饰器是可选的。本章节将解释如何(避免)使用它们。

使用装饰器的优势:

样板文件最小化,声明式代码。
易于使用和阅读。大多数 MobX 用户都在使用。

Babel中启用装饰器

安装依赖
npm i –save-dev babel-plugin-transform-decorators-legacy

编辑package.json,添加plugins,修改后如下

1
2
3
4
5
6
7
8
"babel": {
"presets": [
"react-app"
],
"plugins": [
"transform-decorators-legacy"
]
},

在index.js文件中注入store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { HashRouter } from 'react-router-dom';
import { Provider } from 'mobx-react';
import ResumeStore from './store/ResumeStore';
let stores = {
ResumeStore,
};

ReactDOM.render((
<Provider {...stores}>
<HashRouter>
<App />
</HashRouter>
</Provider>
),document.getElementById('root'));
registerServiceWorker();

配置react-router

安装react-router

npm install –save react-router

App.js文件中配置路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { Component } from 'react';
import './App.less';
import {
Route,
Switch,
} from 'react-router-dom'
import Index from './page/Index';

class App extends Component {
render() {
return (
<div>
<Switch>
<Route path="/" component={Index} />
</Switch>
</div>
);
}
}

export default App;

配置 less

安装依赖

npm install less-loader less –save-dev

修改配置文件

修改 config文件夹下的 webpack.config.dev.js 和 webpack.config-prod.js

  1. test: /.css$/ 改为 /.(css|less)$/
  2. test: /.css$/ 的 use 数组配置增加 less-loader

修改后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{
test: /\.(css|less)$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
{
loader: require.resolve('less-loader') // compiles Less to CSS
}
],
}