一、通過umi來搭建app(如果已新建項目請?zhí)^此步驟)
- 創(chuàng)建目錄放可,初始化umi
mkdir react-pxtovw && cd react-pxtovw
yarn create umi
創(chuàng)建的時候選擇app就足夠了谒臼,然后也使用typescript
- 安裝依賴
yarn
二、使用vw來實現(xiàn)自適應(yīng)
- 在
html
文件的<head></head>
標(biāo)簽內(nèi)插入以下代碼:
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no,width=device-width">
PS: 如果沒有找到html文件吴侦,需要新建 src/pages/document.ejs
2.安裝依賴
cnpm install -D postcss-import postcss-url cssnano-preset-advanced
cnpm install -S postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext cssnano postcss-viewport-units
3.引入和配置
打開且修改.umirc.ts`文件:
// 引入步驟2安裝的依賴們
import postcssImport from 'postcss-import';
import postcssUrl from 'postcss-url';
import postcssAspectRatioMini from 'postcss-aspect-ratio-mini';
import postcssWriteSvg from 'postcss-write-svg';
import postcsscssnext from 'postcss-cssnext';
import pxToViewPort from 'postcss-px-to-viewport';
import cssnano from 'cssnano';
const config: IConfig = {
// 這里省略了很多...
// 額外的postcss插件用這個extraPostCSSPlugins:
extraPostCSSPlugins: [
postcssImport({}),
postcssUrl({}),
postcssAspectRatioMini({}),
postcssWriteSvg({ utf8: false }),
postcsscssnext({}),
pxToViewPort({
viewportWidth: 720, // (Number) The width of the viewport.
viewportHeight: 1280, // (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.
}),
cssnano({
preset: "advanced",
autoprefixer: false,
"postcss-zindex": false,
zindex: false
})
],
}
PS:用到的 extrapostcssplugins 屋休。—— 定義額外的 PostCSS 插件备韧,格式為數(shù)組劫樟。
三、show me the code
寫個div织堂,目錄地址為:react-pxtovw/src/pages/index.tsx
:
<div className={styles.test}>測試</div>
再編寫下css樣式叠艳,目錄地址為:react-pxtovw/src/pages/index.css
:
.test {
display: inline-block;
width: 500px;
height: 500px;
line-height: 500px;
text-align: center;
color: #fff;
background: pink;
}
頁面展示
寫的是px,編譯后自動轉(zhuǎn)為vw