基於react/vue的移動端終極適配方案(更新css-modules配置)

Ghan發表於2019-03-04

先上github地址 https://github.com/gaohan1994/react-vw-layout 有空點個贊蛤~~

2018-4-19日更新適配到安卓低版本的外掛buggyfill(是我疏忽導致大家以為vw解決方案相容範圍過小,原第六步css-modules改為buggyfill,css-modules順延為第七步)

2018-4-16日更新css-modules配置,前面步驟不變,可直接跳到第七步。

寫在前面的話

在接觸到大漠先生牽頭開發的vw解決方案之前,我使用的是阿里的第一代適配解決方案 lib-flexible 在使用vw解決方案開發一套H5之後,我真正的被vw的威力所折服。 由於大漠先生只給出了vue-cli的配置方式,並未給出react系列對應腳手架create-react-app配置版本,在看過大漠先生的配置之後,我在create-react-app腳手架生成的專案上進行了一套配置,使得使用react的各位師兄弟也可以使用vw解決方案! 話不多說開工

vue使用方式:《如何在Vue專案中使用vw實現移動端適配》 關於具體如何使用請參考 再聊移動端頁面的適配 使用Flexible實現手淘H5頁面的終端適配

移動端適配最接近完美的解決方案在react中的使用方式。本文只講create-react-app建立的專案如何配置,具體每個外掛的用途和使用方法請先查閱大漠先生的文章,我相信大漠先生的文章已經講的很明白。

《如何在Vue專案中使用vw實現移動端適配》

《如何在Vue專案中使用vw實現移動端適配》

《如何在Vue專案中使用vw實現移動端適配》

重要的事情說三遍。一定要先大概看一下大漠先生的文章再往下看,否則可能會一頭霧水。

1.建立專案

create-react-app react-vw-layout
cd react-vw-layout
npm start
複製程式碼

開啟http://localhost:3000/ 可以看到react歡迎頁面,第一步成功。

2.開啟配置選項

由於react預設隱藏webpack配置需要手動顯示。

npm run eject
//Are you sure you want to eject? This action is permanent. (y/N) 
y
複製程式碼

執行完eject之後專案結構如下

專案結構.png

第二步收工,第三部開始配置各種外掛。

3.增加配置

安裝postCss外掛

npm i --save postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano
複製程式碼

config/webpack.config.dev.js檔案中進行如下修改

1.引入postCss外掛

const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');
const postcssPxToViewport = require('postcss-px-to-viewport');
const postcssWriteSvg = require('postcss-write-svg');
const postcssCssnext = require('postcss-cssnext');
const postcssViewportUnits = require('postcss-viewport-units');
const cssnano = require('cssnano');
複製程式碼

2.加入postCss配置

加入配置程式碼位置如下

{
    test: /\.css$/,
    use: [
      require.resolve('style-loader'),
      {
        loader: require.resolve('css-loader'),
        options: {
          importLoaders: 1,
        },
      },
      {
        loader: require.resolve('postcss-loader'),
        options: {
          // Necessary for external CSS imports to work
          // https://github.com/facebookincubator/create-react-app/issues/2677
          ident: 'postcss',
          plugins: () => [
            require('postcss-flexbugs-fixes'),
            autoprefixer({
              browsers: [
                '>1%',
                'last 4 versions',
                'Firefox ESR',
                'not ie < 9', // React doesn't support IE8 anyway
              ],
              flexbox: 'no-2009',
            }),
            //加入地點
            //加入地點
            //加入地點
          ],
        },
      },
    ],
},	
複製程式碼

需要加入的程式碼如下


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 
})

複製程式碼

第三步收工。

4.測試

修改App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        hello vw-layout
      </div>
    );
  }
}
export default App;
複製程式碼

修改App.css

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

重新npm start頁面顯示如下

測試demo.png

可以說是非常OK,剩下最後一個問題,配置生產環境webpack配置檔案。

5.配置生產環境webpack.config.js

操作與配置測試環境檔案相同先引入外掛,在相同的位置配置postCss外掛 配置完成後執行npm run build 開啟static/css/main.********.css

打包後的css.png
可以看到已經成功編譯,打完收工

6.加入viewport-units-buggyfill配置

這一步不過在大漠先生的文章中或是我自己的專案中都已經配置,系我自己的疏忽忘記寫在文章中導致大家以為vw相容範圍小。抱歉!!!

開啟public/index.html

首先在<head></head>中引入阿里cdn

<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>
複製程式碼

最終index.html如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      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>
    <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>
  </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`.
    -->
    <script>
      window.onload = function () {
        window.viewportUnitsBuggyfill.init({
          hacks: window.viewportUnitsBuggyfillHacks
        });
      }
    </script>
  </body>
</html>

複製程式碼

重新執行npm start開啟頁面發現:

基於react/vue的移動端終極適配方案(更新css-modules配置)

如果遇到img無法顯示,則新增全域性css

img { 
    content: normal !important; 
}
複製程式碼

OK配置成功。這樣就適配了低版本安卓機型

7.加入css-modules配置

一般的小專案不使用css-modules已經可以hold住了,但是頁面多起來還是建議使用css-modules,下面介紹一下用法:

執行npm i --save react-css-modules

App.js檔案中引入外掛 import CSSModules from 'react-css-modules';

修改css檔案的引入方式 從import './App.css';修改為import styles from './App.css';

修改引用Css方式 className=>styleName

修改匯出方式 export default App=>export default CSSModules(App, styles);

儲存,從新執行npm start檢視頁面發現失敗

clipboard.png

原因是未開啟css import配置,此時import styles from './App.css';該語句並未成功引入css檔案。

開啟webpack.config.dev.js加入modules: true 找到如下位置

{
    test: /\.css$/,
    use: [
      require.resolve('style-loader'),
      {
        loader: require.resolve('css-loader'),
        options: {
          //看這裡看這裡看這裡看這裡
          modules: true,
          
          importLoaders: 1,
        },
      },
      {
        loader: require.resolve('postcss-loader'),
        options: {
           //.....省略
        }
      }
    ],
  },
複製程式碼

儲存,再次執行npm start檢視頁面

clipboard.png
成功!但是這個class名太過亂碼不適於除錯,再次開啟webpack.config.dev.js 找到如下位置加入語句localIdentName:'[name]_[local]_[hash:base64:5]'

{
    test: /\.css$/,
    use: [
      require.resolve('style-loader'),
      {
        loader: require.resolve('css-loader'),
        options: {
          modules: true,
          importLoaders: 1,
          //看這裡看這裡看這裡
          localIdentName: '[name]_[local]_[hash:base64:5]'
        },
      },
      {
        loader: require.resolve('postcss-loader'),
        options: {
           //.....省略
        }
      }
    ],
  },
複製程式碼

再次執行npm start檢視頁面

clipboard.png

OJBK大功告成!

最後相同步驟加入到webpack.config.prod.js中 執行npm run build 檢視打包檔案

clipboard.png

彳亍吧,OK了。

END.其他想說的話

git地址再發一次,希望有空能幫忙點個贊~謝謝~~!! https://github.com/gaohan1994/react-vw-layout 沒有配置成功的可以參考一下。尤其是css-modules可能改的地方比較多。

當初看到大漠先生的vw適配方案真的是眼前一亮,在嘗試了之後覺得這套方案的生產力非常強悍,其實按照本文進行配置已經可以滿足相當一部分專案,除了一點就是沒有使用css-modules,當然我自己已經成功配置了css-modules要修改的地方比較多,以後會出一篇文章來再繼續分享,同時我是個Typescript重度患者!我極度作死的成功配置了create-react-app typescript versionvw + css-modules版本,現在回想起來配置的那幾天真的生不如死。。。各種 踩坑。 等如果有人需要ts + react + vw 解決方案的時候我再寫一篇文章吧。 那就到這裡了,希望大家使用vw解決方案玩的愉快!

相關文章