从0到1搭建react工程二(antd集成与css预处理配置以及路由配置)
新增依赖
dependencies
- antd
- react-router-dom
devDependencies
- less
- less-loader
- style-loader
- css-loader
- babel-plugin-import
antd组件动态引入配置
新增.babelrc
配置
// .babelrc
{
"plugins": [
["import", {
"libraryName": "antd",
"style": true // 表示引入less文件
}]
]
}
新增webpack.config.js
配置
// webpack.config.js
module: {
rules: [
//...
{
test: /\.(css|less)/,
use: ['style-loader', 'css-loader', {
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}]
}
]
}
更新index.js
import React from 'react';
import ReactDom from 'react-dom';
import { Button } from 'antd';
import './index.less';
ReactDom.render(
<div className="wrapper"><Button type="primary">按钮</Button></div>,
document.getElementById('app')
);
.wrapper {
padding: 24px;
text-align: center;
}
效果如下图所示????
添加路由
// router.js
import React from 'react';
import { HashRouter as Router, Route, Switch } from "react-router-dom";
// 新增Page/Index Page/Example Page/Error页面
import IndexComponent from './Pages/Index';
import Example from './Pages/Example';
import ErrorPage from './Pages/Error';
const routeConfig = [
{
path: '/',
component: IndexComponent,
},
{
path: '/example',
component: Example,
}
]
const routes = (
<Router>
<Switch>
{
routeConfig.map(item => (
<Route {...item} exact key={item.path} />
))
}
<Route component={ErrorPage} />
</Switch>
</Router>
)
export default routes;
再次更新index.js
import React from 'react';
import ReactDom from 'react-dom';
import routes from './router';
import './index.less'
ReactDom.render(routes, document.getElementById('app'));
添加新路由页面
// Page/Index
import React from 'react';
import { Button } from 'antd';
import { Link } from 'react-router-dom';
const IndexComp = (props) => {
return (
<div className="wrapper">
go to
<Button type="primary"><Link to="/example">Example</Link></Button>
page
</div>
)
}
export default IndexComp;
// Page/Example
import React from 'react';
import { Button } from 'antd';
import { Link } from 'react-router-dom';
const IndexComp = (props) => {
return (
<div className="wrapper">
go to
<Button type="primary"><Link to="/example">Example</Link></Button>
page
</div>
)
}
export default IndexComp;
效果如下图????