react create-react-app v5 configures px2rem (exposed eject mode)

Environmental information:

create-react-app v5
“react”: “^18.2.0”
“postcss-plugin-px2rem”: “^0.8.1”

Configuration steps:

My method is npm run eject to expose webpack configuration
1. Install postcss-plugin-px2rem and lib-flexible

cnpm install postcss-plugin-px2rem  lib-flexible --save

2. Configure config/webpack.config.js
and add this code:

//px2rem的配置
const px2rem = require("postcss-plugin-px2rem");
const px2remOpts = {
    
    
	rootValue: 37.5, //这个值定义了1rem应该等于多少像素。在这里,1rem等于37.5
	exclude: /(node_module)/, //这是一个正则表达式,用于指定哪些文件应该被排除在转换之外。在这里,所有在'node_module'目录下的文件都将被排除。
	// mediaQuery: false, //这个选项表示是否应该在媒体查询中转换px单位。在这里,它被设置为false,意味着媒体查询中的px单位将不会被转换
	// minPixelValue: 3, //这个选项表示应该转换的最小px值。在这里,只有px值大于或等于3的才会被转换
};

Then add the configuration in getStyleLoaders (search for getStyleLoaders), and
add it in postcssOptions under postcss-loader

[
  px2rem(px2remOpts)
],

Same level as postcss-preset-env.
This is where you can see the screenshot:
Insert image description here

This complete code:

      {
    
    
        // Options for PostCSS as we reference these options twice
        // Adds vendor prefixing based on your specified browser support in
        // package.json
        loader: require.resolve('postcss-loader'),
        options: {
    
    
          postcssOptions: {
    
    
            // Necessary for external CSS imports to work
            // https://github.com/facebook/create-react-app/issues/2677
            ident: 'postcss',
            config: false,
            plugins: !useTailwind
              ? [
                  'postcss-flexbugs-fixes',
                  [
                    'postcss-preset-env',
                    {
    
    
                      autoprefixer: {
    
    
                        flexbox: 'no-2009',
                      },
                      stage: 3,
                    },
                  ],
                  [
                    px2rem(px2remOpts)
                  ],
                  // Adds PostCSS Normalize as the reset css with default options,
                  // so that it honors browserslist config in package.json
                  // which in turn let's users customize the target behavior as per their needs.
                  'postcss-normalize',
                ]
              : [
                  'tailwindcss',
                  'postcss-flexbugs-fixes',
                  [
                    'postcss-preset-env',
                    {
    
    
                      autoprefixer: {
    
    
                        flexbox: 'no-2009',
                      },
                      stage: 3,
                    },
                  ],
                ],
          },
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        }
      } 

3. In src/index.js (the entry file introduces import 'lib-flexible';)
The entry file introduces import 'lib-flexible';
4. In public/index.html, comment the meta and add a piece of compatible code that is compatible with ipad and ipad pro.

Comment out (the reason for commenting is that lib-flexible will automatically create meta):

<meta name="viewport" content="width=device-width, initial-scale=1" />

Add (ipad and ipad pro) to the head:

<!-- 淘宝弹性布局方案lib-flexible不兼容ipad和ipad pro的解决方法 -->
    <script>
    /(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));
    </script>

This code is used to detect whether the user is using an Apple device such as iPhone, iPad, iPod or iOS. If so, it creates a new viewport meta tag and adds it to the head of the HTML document. The content of the viewport meta tag is set to 'target-densitydpi=device-dpi, width=480px, user-scalable=no', which means it will try to make the page look similar on various devices, and the width of the page is set to 480px, and the user cannot manually zoom the page.

My index.html code is as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1" /> -->
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
    <!-- 淘宝弹性布局方案lib-flexible不兼容ipad和ipad pro的解决方法 -->
    <script>
    /(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));
    </script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
  
</html>

index.html screenshot
5. Re-run npm start and inspect the element to see if px has been converted to rem. If the conversion is successful, the configuration is successful.
You can add a div in App.js and then write a width and height in App.css and then use it on the div.

.box{
    
    
  width: 100px;
  height: 100px;
  background: red;
}

test code
Screenshot of the effect after running:
converted from 100px to 1.333rem. When switching, it also becomes larger and smaller.
Screenshot of the effect after running

Guess you like

Origin blog.csdn.net/weixin_44058725/article/details/133378259