首先安装处理css的一些依赖:
1、css-loader,style-loader //处理css基础loader
2、node-sass,sass-loader //处理sass
3、postcss-loader,autoprefixer //自动给css样式添加前缀,兼容浏览器
4、mini-css-extract-plugin //提取css
5、optimize-css-assets-webpack-plugin //压缩css的
"devDependencies": { "autoprefixer": "^9.6.1", "css-loader": "^3.2.0", "mini-css-extract-plugin": "^0.8.0", "node-sass": "^4.12.0", "optimize-css-assets-webpack-plugin": "^5.0.3", "postcss-loader": "^3.0.0", "sass-loader": "^8.0.0", "style-loader": "^1.0.0" }
webpack.config.js文件代码
const webpack = require('webpack') const path = require('path') const HtmlwebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin") const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { mode:'development', entry: './src/main.js', output:{ path:path.join(__dirname,'dist'), filename:'[name].[hash].js' }, resolve:{ extensions: ['.js', '.json', '.vue', '.scss', '.css'], alias:{ 'vue': 'vue/dist/vue.min.js', '@':path.join(__dirname,'src'), '@static':path.join(__dirname,'static') } }, module:{ rules:[{ test:/\.(sa|sc|c)ss$/, use: [ { loader: MiniCssExtractPlugin.loader, options: {} }, { loader: "css-loader" // 将 CSS 转化成 CommonJS 模块 }, { loader: "sass-loader" // 将 Sass 编译成 CSS }, { loader: "postcss-loader" // 将 Sass 编译成 CSS } ] },{ test: /\.vue$/, loader: 'vue-loader' },{ test: /\.js$/, use: ['babel-loader'], exclude: /node_modules/ }] }, plugins:[ new VueLoaderPlugin(),//处理vue文件 new MiniCssExtractPlugin({//提取css filename:'[name].css' , // chunkFilename: isDev ? '[id].css' : 'static/css/[id].[chunkhash:8].css', }), new OptimizeCssAssetsPlugin()//压缩css ] }
这里代码里我们夹杂着处理vue文件和js文件的配置,如果不用可以去掉.
关于处理css前缀,在根目录创建postcss.config.js文件,里面贴如如下代码
module.exports = { plugins : [ require('autoprefixer')({overrideBrowserslist: ['> 0.15% in CN']})// 自动添加css前缀 ] };