依赖
webpack编译scss需要用到这几个loader:style-loader,css-loader,postcss-loader,sass-loader以及插件:extract-text-webpack-plugin
安装相关loader和插件:
npm install style-loader css-loader postcss-loader sass-loader extract-text-webpack-plugin
postcss-loader
postcss-loader是为了兼容多个浏览器需要在一些css上添加兼容前缀。在项目下添加postcss.config.js,内容如下:
module.exports = {
plugins: [
require('autoprefixer')({ /* ...options */ })
]
}
webpack.config.js
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
entry: __dirname + '/app/main.js',
},
resolve: {
extensions: ['.js','.css', '.scss', '.html'],
},
module: {
rules: [
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: ['css-loader?minimize!postcss-loader']
})
},
{
test: /\.(scss|sass)$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: ['css-loader?minimize','postcss-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: '[name].[contenthash:5].css',
allChunks: true
})
]
};
需要注意的是:配置scss编译的loader是从右到左执行:
- 先执行sass-loader ,把scss文件编译为css
- 接着执行postcss-loader,为css添加兼容相关的前缀
- 最后执行css-loader,在css-loader后加了minimize参数,是为了压缩css
- 如果失败,默认执行style-loader