Mobile terminal adaptation (vw)

Adaptation overview

Why adapt?

  • In order to make the mobile project page we develop, keep the same proportion in mobile devices (mobile phones) of different sizes

Adaptation principle

  • Select the size of a mobile phone as the benchmark, and scale other mobile phones in equal proportions
  • The general choice iPhone 6(2 times the screen), the screen width is:375px

Adaptation method

  • rem: need to manually modify the htmlelement font-size; additionally bodyset the font size of the element to the normal value
  • vw: 1 vwequal to the width of the screen1%

solution

See the postcss-px-to-viewport documentation for related package information

  1. Install the px to vw package:

npm i -D postcss-px-to-viewport

-   包的作用:将 `px` 转化为 `vw`,所以有了该工具,只需要在代码中写 `px` 即可
复制代码
  1. craco.config.jsadd the corresponding configuration

    const pxToViewport = require('postcss-px-to-viewport')
    const vw = pxToViewport({
      // 视口宽度,一般就是 375( 设计稿一般采用二倍稿,宽度为 375 )
      viewportWidth: 375
    })
    
    module.exports = {
      // 此处省略 webpack 配置
      webpack: {...},
    
      // 这里补充style配置
      style: {
        // postcss: {
        //  plugins: [vw]
        // },
        postcss8的新写法
        postcss: {
          mode: 'extends',
          loaderOptions: {
            postcssOptions: {
              ident: 'postcss',
              plugins:[vw]
            }
          }
        }
      }
    }
    复制代码
  2. Restart the project for the configuration to take effect

Notice

If the adaptation effect does not take effect, it may be a version problem

The react-scripts in react scaffolding has been upgraded to version 5.0, and its internal webpack has also been upgraded to 5.0 (the configuration of postcss in webpack 5.0 postcss-px-to-viewportis incompatible with the current configuration)

We currently use third-party tools @craco/cracoto configure webpack, but it does not provide a matching upgrade plan in time

So, there is an option: fall back to"react-scripts": "^4.0.3", "@craco/craco": "^6.4.2",

npm uninstall react-scripts
npm install [email protected]
复制代码

Or directly configure as follows

        const pxToViewport = require('postcss-px-to-viewport')
    const vw = pxToViewport({
      // 视口宽度,一般就是 375( 设计稿一般采用二倍稿,宽度为 375 )
      viewportWidth: 375
    })

    module.exports = {
      // 此处省略 webpack 配置
      webpack: {...},

      // 这里补充style配置
      style: {
        // postcss: {
        //  plugins: [vw]
        // },
        //  postcss8的新写法
        postcss: {
          mode: 'extends',
          loaderOptions: {
            postcssOptions: {
              ident: 'postcss',
              plugins:[vw]
            }
          }
        }
      }
    }
复制代码

Guess you like

Origin juejin.im/post/7085687045259001869