create-react-app作为最常用的react脚手架集成了很多的常用功能,比如支持es6
、JSX
、动态import
、Fetch(polyfill)
、proxy
、postcss
、eslint
等。但也有些功能并没有提供支持比如Hot-reloading
和css预处理器
,所以我们需要自定义配置这些功能。
首先需要npm run eject
进行自定义配置。
配置proxy
在package.json中添加proxy字段

在
index.js
中实现代理功能
npm start
打开控制台请求数据成功
配置css预处理less/sass
首先安装对应的loader
yarn add less-loader less --dev
yarn add sass-loader node-sass --dev
修改dev环境的配置


然后修改生成环境下的配置,修改方法同上,sass的配置同理。

配置模块热更新
模块热更新通俗的说就是不刷新页面更新的模块自己更新。
首先 yarn add react-hot-loader --dev
,然后再webpack.config.dev.js中添加

在babel-loader中添加一个plugins。

修改入口文件代码如下
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { AppContainer } from 'react-hot-loader';
// ReactDOM.render(<App />, document.getElementById('root'));
const render = Component => {
ReactDOM.render(
<AppContainer>
<Component></Component>
</AppContainer>,
document.getElementById('root')
)
}
render(App);
if(module.hot) {
module.hot.accept('./App',() => {
render(App);
});
}
registerServiceWorker();
//之前实验proxy代理的代码
fetch('/api/comments/show?id=4199740256395164&page=1')
.then(res => {
res.json().then(data => {
console.log(data)
})
})
这样就完成了热更新的配置。
网友评论