在實際開發中,我們需要將設計稿中的
px
轉換成rem
,然後再寫入到樣式中。postcss-px2rem
可以幫助我們自動完成轉換。
一、安裝模塊
cnpm install amfe-flexible postcss-px2rem -S
- amfe-flexible:是
rem
的適配插件。(例:750px == 10rem) - postcss-px2rem:負責將輸入的
px
自動轉爲rem
。
二、入口文件main.js
裏引入amfe-flexible
import "amfe-flexible";
三、以下配置二選一即可:
1、在項目根目錄創建vue.config.js文件,並完成以下配置:
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [
// 設計稿寬度的1/10,一般爲75
require('postcss-px2rem')({remUnit: 75}),
]
}
}
}
}
2、我們也可以打開package.json,增加以下配置:
"postcss": {
"plugins": {
"autoprefixer": {},
"postcss-px2rem": {
"remUnit": 75
}
}
}
- 配置的
remUnit
設置爲75(設計稿寬度的1/10),表示75px將會轉化爲1rem。
四、重啓項目
cnpm run serve