yarn add create-react-app
create-react-app 项目名称
不使用 eject
[email protected]需要 customize-cra
yarn add react-app-rewired customize-cra -D
在根目录下创建名为 config-overrides.js 的相关配置文件,配置内容如下
const { override, fixBabelImports } = require('customize-cra');
module.exports = override();
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
"eject": "react-scripts eject"
},
yarn add postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano cssnano-preset-advanced
const { override} = require('customize-cra');
const rewireLess = require('react-app-rewire-less');
const addCustomize = () => config => {
require('react-app-rewire-postcss')(config, {
plugins: loader => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
require('postcss-aspect-ratio-mini')({}),
require('postcss-px-to-viewport')({
viewportWidth: 750, // (Number) The width of the viewport.
viewportHeight: 1334, // (Number) The height of the viewport.
unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
viewportUnit: 'vw', // (String) Expected units.
selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px.
minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
mediaQuery: false // (Boolean) Allow px to be converted in media queries.
}),
require('postcss-write-svg')({
utf8: false
}),
require('postcss-viewport-units')({}),
require('cssnano')({
preset: "advanced",
autoprefixer: false,
"postcss-zindex": false
})
]
});
return config;
}
module.exports = override(
addCustomize(),
);
在 index.html中''标签添加
<script src="//g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js"></script>
在body中添加 js
<script>
window.onload = function () {
window.viewportUnitsBuggyfill.init({
hacks: window.viewportUnitsBuggyfillHacks
});
}
</script>
yarn add less less-loader
注意: less-loader 版本6.0 之前与之后配置方式不同
可能引发一下错误:
ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema
const { override, addLessLoader } = require('customize-cra');
module.exports = override(
addLessLoader({
// javascriptEnabled: true, less-loader 6.0 之前
lessOptions: {
javascriptEnabled: true,
},
}),
addCustomize(),
);