1.下载lib-flexible
我使用的是vue-cli+webpack,所以是通过npm来安装的
npm i lib-flexible --save
2.引入lib-flexible
在main.js中引入lib-flexible
import 'lib-flexible/flexible'
3.设置meta标签
通过meta标签,设置设备宽度以及缩放比例
<meta name="viewport" content="width=device-width, initial-scale=1.0">
4.安装px2rem-loader
npm install px2rem-loader
5.配置px2rem-loader
这里是重要的一步~~
在build文件中找到util.js,将px2rem-loader添加到cssLoaders中,如:
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 75
}
}
同时,在generateLoaders方法中添加px2remLoader
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader, px2remLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
6.重启,一切ok~
当配置完之后,只需要重启下服务,就自动转化为rem了
npm run dev