本文重点:
项目环境搭建此处省略,不再赘述,需要的请查阅相关资料。
本篇只介绍,如果在vue+webpack
的项目中配置,把px自动转为rem
第一步安装:
npm install postcss-px2rem postcss --save
第二步: 在 webpack.base.conf.js
中 引入
const webpack = require('webpack')
const px2rem = require('postcss-px2rem')
const postcss = require('postcss')
第三步 在module
中添加如下代码:需要
把下面的代码:
//此插件是自动把px换算成rem
plugins: [
new webpack.LoaderOptionsPlugin({
// webpack 2.0之后, 此配置不能直接写在自定义配置项中, 必须写在此处
vue: {
postcss: [require('postcss-px2rem')({ remUnit: 75, propWhiteList: [] })]
},
})
]
添加到:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
const webpack = require('webpack')
const px2rem = require('postcss-px2rem')
const postcss = require('postcss')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
},
{
test: /\.(css|less|scss)(\?.*)?$/,
loader: 'style-loader!css-loader!sass-loader!less-loader!postcss-loader'
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
},
plugins: [
new webpack.LoaderOptionsPlugin({
// webpack 2.0之后, 此配置不能直接写在自定义配置项中, 必须写在此处
vue: {
postcss: [require('postcss-px2rem')({ remUnit: 37.5, propWhiteList: [] })]
},
})
]
}
注意:这里是以750px(iphone6)宽度为基准,所以remUnit为37.5
第四步 在rules
中加如下代码,css
我是用到sass
,less
,所以需要引入对应的loader
,不需要的可不写。
{
test: /\.(css|less|scss)(\?.*)?$/,
loader: 'style-loader!css-loader!sass-loader!less-loader!postcss-loader'
}
第五步:在你的项目中测试 加入一下css
浏览器上会自动转换
编写的代码:
img{
width: 200px;
height: 200px;
}
浏览器上显示的代码:
img {
width: 2.666667rem;
height: 2.666667rem;
}