在 vue-cli 4.x 中如何配置 postcss-plugin-px2rem 进行移动端开发?如何配置 autoprefixer 进行样式预处理?
在项目 vue-cli 4 创建的 vue 项目根目录下创建 vue.config.js 文件,系统会自动检测此配置文件,然后配置如下:
'use strict'
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/', // The value can also be set to an empty string ('') or a relative path (./) so that all assets are linked using relative paths.
outputDir: 'dist',
assetsDir: 'static',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: { // 配置反向代理用于与后端接口进行联调
// detail: https://cli.vuejs.org/config/#devserver-proxy
'/dev-api': {
target: 'http://www.xxx你的接口地址xxx.com',
changeOrigin: true,
pathRewrite: {
'^/dev-api': ''
}
}
}
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
resolve: {
alias: {
'@': resolve('src')
}
}
},
css: {
loaderOptions: {
postcss: {
plugins: [
require('autoprefixer')({ // 配置使用 autoprefixer
// browsers: ['last 20 versions'],
overrideBrowserslist: ['last 20 versions'] // 记得这里要把 browsers 改为 overrideBrowserslist,autoprefixer 新版本的写法有变
}),
require('postcss-plugin-px2rem')({ // 配置使用 postcss-plugin-px2rem 把 px 单位转成 rem,当然项目 main.js 中要相应 import 'amfe-flexible' 作为移动端的自适应解决方案
rootValue: 75,
unitPrecision: 8,
propWhiteList: [],
propBlackList: [],
selectorBlackList: [],
ignoreIdentifier: false,
replace: true,
mediaQuery: false,
minPixelValue: 2
})
]
}
}
}
}
如果出现警告 Replace Autoprefixer browsers option to Browserslist config. Use browserslist key in package.json or .browserslistrc file... 请看上面 autoprefixer 的配置,记得这里要把 browsers 改为 overrideBrowserslist,autoprefixer 新版本的写法已经有变。