(移動端適配px轉rem)react配置rem外掛lib-flexible和postcss-px2rem-exclude

起風了發表於2022-01-27

1、安裝外掛

yarn add lib-flexible postcss-px2rem-exclude

//這個外掛也要下,不然的話啟動專案的時候會報錯
yarn add react-app-rewire-postcss

2、修改config-overrides.js(如果沒有就新建,在專案根目錄) 在config-overrides.js檔案裡重寫postcss,加入如下程式碼
這檔案將antd-mobile的配置合併起來了,如果你用了antd-mobile的按需引入,那直接貼上過去就ok,antd-mobile按需引入參照官網https://mobile.ant.design/doc...

const {
    override,
    fixBabelImports,
    addWebpackAlias,
    addDecoratorsLegacy,
} = require("customize-cra");
const path = require("path");
const rewirePostcss = require("react-app-rewire-postcss");
const px2rem = require("postcss-px2rem-exclude");
module.exports = override(
    fixBabelImports("import", {
        libraryName: "antd-mobile",
        style: "css",
    }),
    addWebpackAlias({
        "@": path.resolve(__dirname, "src"),
    }),
    addDecoratorsLegacy(),
    (config, env) => {
        // 重寫postcss
        rewirePostcss(config, {
            plugins: () => [
                require("postcss-flexbugs-fixes"),
                require("postcss-preset-env")({
                    autoprefixer: {
                        flexbox: "no-2009",
                    },
                    stage: 3,
                }),
                //關鍵:設定px2rem
                px2rem({
                    remUnit: 37.5,//這裡最開始寫的是75,但是antd的樣式變的可小,查詢後看人家設定的是37.5,然後試了下確實好了
                    exclude: /node-modules/i,
                }),
            ],
        });

        return config;
    }
);

3、入口檔案index.js 中引入lib-flexible
import "lib-flexible"

4、最後一步修改index.html

<meta content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport" />

相關文章