我的本地环境是vue2.9
1、安装
npm install px2rem-loader -D
npm install lib-flexible -S
2、在main.js导入lib-flexible文件
import 'lib-flexible'
3、在build文件下的utils.js文件进行配置
我们只需在utils.js中加入px2remLoader和generateLoaders 函数如下:
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const px2remLoader = {
loader: 'px2rem-loader',
options: {
remUnit: 192,//remUnit的意思是1rem=多少像素,结合lib-flexible的方案将remUnit设置成设计搞宽度的1/10,我这项目的设计搞宽度是1920px.
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader, px2remLoader] : [cssLoader, px2remLoader]//将px2remLoader放入loaders 数组中
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)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
4、修改flexible.js文件
在node_module下找到lib-flexible文件中的flexible.js文件中的refreshRem方法
function refreshRem(){
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
//需修改 width = 540 * dpr;这里是设置成了当屏幕宽度大于540的时候把屏幕宽度写死了,我们需要动态变化所以得改过来不能写死,改成如下:
//width = 540 * dpr;
width = width * dpr;
}
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
网友评论