跟我一塊兒使用create-react-app腳手架搭建vw-layout解決方案

以前也是看過大漠的vw適配Vue-cli,我本身寫H5,還有使用vue作項目的時候,會搭建大漠博客中的那一套。
如今在github上面,看見了一位博主使用create-react-app也是用vw適配,很是開心,如今咱們一塊兒使用vw給react適配移動端項目吧~
先放上博主大大的開源地址:https://github.com/gaohan1994/react-vw-layout
給各位無私開源的程序員們點贊,大家是最可愛的人兒。
1.建立項目css

cnpm install -g create-react-app
create-react-app react-vw-layout
cd react-vw-layout
npm start

2..打開配置選項
因爲react默認隱藏webpack配置須要手動顯示。
eject完的項目以下

第二步收工,第三部開始配置各類插件。
3.增長配置
安裝postCss插件html

cnpm i --save postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano

在config/webpack.confi.js文件中進行以下修改
1.引入postCss插件vue

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配置react

加入配置代碼位置以下android

{
        // 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,
            }),
            // 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.
            // postcssNormalize()
            // 加入地點
            // 加入地點
          ],
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
      },

須要加入的代碼以下webpack

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.jsgit

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

接下來運行項目,運行項目會報錯

解決辦法爲:github

cnpm i cssnano-preset-advanced --save-dev

運行項目
web

5.生產環境打包項目
使用npm run build報錯

解決辦法爲修改package.json文件

[
    "last 2 versions",
    "android 4",
    "opera 12"
  ],

接下來打包項目成功

打開static/css/main.********.css

6.加入viewport-units-buggyfill配置
打開public/index.html

首先在中引入阿里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以下

//index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut 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="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>
    <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>
    <script>
      window.onload = function () {
        window.viewportUnitsBuggyfill.init({
          hacks: window.viewportUnitsBuggyfillHacks
        });
      }
    </script>
    <!--
      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>

從新執行npm start打開頁面發現:

若是遇到img沒法顯示,則添加全局css

img { 
    content: normal !important; 
}

這樣就適配了低版本安卓機型
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查看頁面發現失敗

緣由是未打開css import配置,此時import styles from './App.css';該語句並未成功引入css文件。

打開webpack.config.js加入modules: true 找到以下位置

{
        loader: require.resolve('css-loader'),
        // options: cssOptions,
        // 代碼看這裏看這裏
        options:{
          //添加添加添加
          modules:true,
          importLoaders:1,
        }
      },

保存,再次執行npm start查看頁面

是這個class名太過亂碼不適於調試,再次打開webpack.config.dev.js 找到以下位置加入語句localIdentName:'[name][local][hash:base64:5]'

{
        loader: require.resolve('css-loader'),
        // options: cssOptions,
        // 代碼看這裏看這裏
        options:{
          //添加添加添加
          modules:true,
          importLoaders:1,
          localIdentName: '[name]_[local]_[hash:base64:5]'
        }
      }

再次運行項目

咱們能夠看到對應的class,方便咱們在項目中的調試
最後咱們執行npm run build 查看打包文件

嗯,已經大功告成啦啦啦啦啦啦啦 開心,再次感謝做者大大無私的分享經驗

相關文章
相關標籤/搜索