我试图弄清楚如何在最终的输出CSS文件上运行postcss。
'strict';
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
/* POSTCSS Optimizations of CSS files */
const clean = require('postcss-clean');
const colorMin = require('postcss-colormin');
const discardDuplicates = require('postcss-discard-duplicates');
const discardEmpty = require('postcss-discard-empty');
const mergeRules = require('postcss-merge-rules');
const mergeLonghand = require('postcss-merge-longhand');
const minifyFonts = require('postcss-minify-font-values');
const orderedValues = require('postcss-ordered-values');
const uniqueSelectors = require('postcss-unique-selectors');
/* EXTRACT CSS for optimization and parallel loading */
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
chunkFilename: '[id].bundle.js',
publicPath: '/dist/',
soureMapFilename: '[file].map'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new StatsPlugin('stats.json'),
new ExtractTextPlugin('assets/css/[name].css?[hash]-[chunkhash]-[contenthash]-[name]', {
disable: false,
allChunks: true
})
],
node: {
net: 'empty',
tls: 'empty',
dns: 'empty'
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname
},
{
test: /\.scss$/i,
loader: ExtractTextPlugin.extract('style', ['css', 'postcss', 'sass'])
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', ['css'])
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}]
},
postcss() {
return [mergeRules, mergeLonghand, colorMin, clean, discardEmpty,
orderedValues, minifyFonts, uniqueSelectors, discardDuplicates];
},
sassLoader: {
includePaths: [path.resolve(__dirname, './node_modules')]
}
};
我当前的配置在编译所有依赖的SASS并将其和静态CSS导入并使用ExtractTextPlugin提取它们时效果很好。
看来我可以在CSS块上运行POSTCSS优化,但不能在最终产品上运行。这意味着我无法摆脱重复的CSS规则。
在sass-loader和extractTextPlugin成功发挥作用之后,如何在最终状态CSS文件上运行POSTCSS?
最佳答案
我在使用ExtractTextPlugin进行类似设置时遇到问题,而我的问题是如何使用ExtractTextPlugin插件。
我仅将其用于生产版本,这对我有用:
module: {
loaders: [
{ // styles
test: /\.scss$/,
include: [ path.join(__dirname, 'source/styles') ],
loader: ExtractTextPlugin.extract('style', ['css', 'postcss', 'sass'])
}
]
},
注意['css','postcss','sass']的数组。那就是我所缺少的部分。该数组将首先解析,然后运行样式,该样式最终将由插件提取。
而且,在插件数组上,我使用
new ExtractTextPlugin('styles-[chunkhash].css')
。