-
初始化脚手架
create-react-app my-app
-
安装依赖
yarn add postcss-px2rem customize-cra react-app-rewired react-app-rewire-postcss
-
在根目录下创建 config.overrides.js
,内容如下
const { override } = require('customize-cra')
const rewirePostcss = require('react-app-rewire-postcss')
module.exports = override((config, env) => {
rewirePostcss(config, {
plugins: () => [
require('postcss-px2rem')({
remUnit: 375 / 10,
exclude: /node-modules/i
})
]
})
return config
})
-
更改 package.json
中的启动命令
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
-
src/utils/
目录下创建 rem.js 或 adapter.js
(响应式判断设备大小,设置不同的根字体大小),内容如下
function adapter() {
const dip = document.documentElement.clientWidth
const rootFontSize = dip / 10
document.documentElement.style.fontSize = rootFontSize + 'px'
}
adapter()
window.onresize = adapter
-
在 scr/index.js
入口文件中直接引入执行 rem.js 或 adapter.js
import './utils/rem.js'
import './utils/adapter.js'
-
最后,重新启动项目
yarn start