# 配置React技术栈
# 基本使用
1、安装React依赖包
npm install --save-dev babel-preset-react react-hot-loader
npm install --save react react-dom
2、配置webpack.config.js支持React
//webpack.config.js
module.exports = {
extensions: ['.js', '.json', '.jsx'],
module: {
rules: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options:{
babelrc:true
}
}
}]
}
}
3、配置.babelrc
// .babelrc
{
"presets": [
["env",
{
"modules": false,
"targets":
{
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-0"
],
"plugins": ["transform-runtime"],
"env":
{
"development":
{
"presets": ["react"],
"plugins": ["react-hot-loader/babel"]
},
"production":
{
"presets": ["react"],
"plugins": []
}
}
}
4、配置React模块热替换(hot module replacement)
CYB默认已集成
webpack-hot-middleware
,由于React本身限制,需要在代码中配置react-hot-loader
启用模块热替换功能(hot module replacement)。详细配置请参考:https://github.com/gaearon/react-hot-loader
//App.js
import { hot } from 'react-hot-loader'; //引入模块热替换
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default hot(module)(App); //配置模块热替换
# 使用.jsx
1、设置cyb.config.js
中的entryExt
的值为.jsx
//cyb.config.js
module.exports = {
entryExt: '.jsx' //脚本入口扩展名 默认为.js
}
配置脚本扩展名需要vue-cli版本 >= v1.5.0。
2、将项目入口脚本扩展名.js
修改.jsx
.
├── README.md
├── cyb.config.js
├── package.json
├── src
│ └── views
│ └── index
│ ├── index.html
│ ├── index.jsx # 修改脚本入口扩展名为.jsx
│ └── module
└── webpack.config.js
# 高级使用
项目中可自行安装react-router-dom
、redux
等扩展
npm install --save react-router-dom react-redux
npm install --save-dev redux-devtools
# 更多参考
redux:https://redux.js.org/
CYB使用Babel编译React代码,Babel的更多配置请参考使用Babel编译