我正在尝试配置mini-css-extract-plugin
以在构建后从SCSS生成单个或大块CSS文件,但是似乎我对webpack不太熟悉,并且在某处失败。
使用“ webpack”:“ ^ 4.29.0”,“ mini-css-extract-plugin”:“ ^ 0.5.0”我设法生成的JS文件应该是CSS文件。
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const isProd = (process.env.NODE_ENV === 'production')
const port = 3000,
host = 'localhost'
const styles = [
{ loader: isProd? MiniCssExtractPlugin.loader : 'style-loader' },
{
loader: 'css-loader',
options: {
sourceMap: !isProd,
modules: true,
}
},
{ loader: 'postcss-loader' },
{
loader: 'sass-loader',
options: {
sourceMap: !isProd,
}
}]
module.exports = {
mode: isProd? 'production': 'development',
entry: ['@babel/polyfill', './src/index.js'],
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: styles
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
exclude: /node_modules/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'content/fonts/'
}
}]
}
]
},
resolve: {
extensions: ['.scss', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([
{ from:'src/content/images', to: 'content/images' },
]),
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body',
}),
new MiniCssExtractPlugin({
chunkFilename: '[name].css',
filename: 'styles.css'
})
],
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
styles: {
name: 'styles',
test: /\.(css|sass|scss)$/,
chunks: 'all',
enforce: true,
minChunks: 1,
reuseExistingChunk: true,
}
}
}
},
devtool: 'source-map',
devServer: {
contentBase: './dist',
hot: true,
host: host,
port: port,
historyApiFallback: true,
compress: true,
}
}
我希望能够生成一个大的CSS文件或多个CSS和文件块。
答案 0 :(得分:0)
问题在于isProd
始终为false,这就是为什么webpack将样式块创建为js文件(styles.bundle.js
)的原因。将isProd
设置为true并尝试一下。它应该工作。实际上,我在机器上尝试过它,但是它确实起作用了。
const isProd = true // just for debugging purpose. (process.env.NODE_ENV === 'production')
还有一件事,我建议不要同时使用Sass和PostCss。我认为这会使您的项目更加复杂。因为我认为您不需要Sass或任何其他带有PostCSS之类的工具的预处理器。但是,如果您坚持这样做,则PostCSS对于sass文件有一个很好的解析器,这样,您的webpack配置至少会更具可读性。祝你好运!