react移動端適配方案實踐

捏泥巴的小人發表於2018-12-22

react移動端適配方案

本文專案基於create-react-app構建。更多移動端資料推薦

tips

/* 處理 vm 適配圖片不顯示問題 */
img {
  content: normal !important; 
}
複製程式碼

1️⃣ 專案初始 + 暴露配置項

  • 1、create-react-app react-vw-layout 初始化專案
  • 2、npm run eject 暴露配置項

2️⃣ postCss外掛安裝配置

package.json 中新增依賴,並安裝


"postcss-aspect-ratio-mini": "0.0.2",
//--坑點 已經更新 postcss-preset-env 所以請使用 "postcss-preset-env": "6.0.6"?
"postcss-cssnext": "^3.1.0",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"postcss-px-to-viewport": "0.0.3",
"postcss-viewport-units": "^0.1.4",
"postcss-write-svg": "^3.0.1"

複製程式碼

config/webpack.config.dev.js 檔案中修改新增配置(開發環境生效) (生產環境打包配置如下,也是一樣的在資料夾 config/webpack.config.prod 中修改)

// config/webpack.config.dev.js
// 檔案頭部引進依賴
const fs = require('fs');
const path = require('path');
const resolve = require('resolve');
const webpack = require('webpack');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const getClientEnvironment = require('./env');
const paths = require('./paths');
const ManifestPlugin = require('webpack-manifest-plugin');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin-alt');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');

// 移動端適配新增 - 插入
const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');
const postcssPxToViewport = require('postcss-px-to-viewport');
const postcssWriteSvg = require('postcss-write-svg');
const postcssCssnext = require('postcss-preset-env'); //這個外掛已經更新 postcss-preset-env 所以請使用 "postcss-preset-env": "6.0.6",
const postcssViewportUnits = require('postcss-viewport-units');
const cssnano = require('cssnano');


//配置項中新增使用

 {
    // 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: {
      // Necessary for external CSS imports to work
      // https://github.com/facebook/create-react-app/issues/2677
      ident: 'postcss',
      plugins: () => [
        require('postcss-flexbugs-fixes'),
        require('postcss-preset-env')({
          autoprefixer: {
            flexbox: 'no-2009',
          },
          stage: 3,
        }),

        // -----插入適配移動端配置項-----?
        postcssAspectRatioMini({}),
        postcssPxToViewport({
          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.
        }),
        postcssWriteSvg({
          utf8: false
        }),
        postcssCssnext({}),
        postcssViewportUnits({}),
        cssnano({
          //舊的 --坑點
          // preset: "advanced",
          // autoprefixer: false,
          // "postcss-zindex": false
          //新配置繼續使用高階配置,按照這個配置
          "cssnano-preset-advanced": {
            zindex: false,
            autoprefixer: false
          },
        })
      ],
    },
},

複製程式碼

3️⃣測試驗證

修改 App.css 檔案

.App {
  width: 750px;
  height: 300px;
  background: #409eff;
  color: #ffffff;
  line-height: 200px;
  text-align: center;
}
複製程式碼

npm start 啟動專案,開啟控制檯,這個時候已經生效了

react移動端適配方案實踐

配置好生產環境之後驗證,npm run build,這個時候,生產打包已經生效了。

react移動端適配方案實踐

4️⃣ 一些兼相容性hacks處理

修改 public/index.html, 引入阿里的 cdn

<!-- index.html body 後新增-->
<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>
<script>
  window.onload = function() {
    window.viewportUnitsBuggyfill.init({
      hacks: window.viewportUnitsBuggyfillHacks
    });

    // 驗證輸出
    const winDPI = window.devicePixelRatio;
    const uAgent = window.navigator.userAgent;
    const screenHeight = window.screen.height;
    const screenWidth = window.screen.width;
    const winWidth = window.innerWidth;
    const winHeight = window.innerHeight;

    console.log(winDPI, "裝置 DPI");
    console.log(uAgent, "客戶端");
    console.log(screenWidth, "螢幕寬度");
    console.log(winHeight, "螢幕高度");
    console.log(winWidth, "Windows Width");
    console.log(winHeight, "Windows Height");
  };
</script>
複製程式碼

react移動端適配方案實踐

至此配置算是完成了,更多其中外掛的配置,還需要了解一下官方的配置使用,此外外掛和可行性方案都會更新,這裡只是作為自己學習實際的一個可行性方案實踐的過程,如果有更多更新方案可以留言告知。謝閱~

相關文章