问题描述
使用webpack 2(或3)时,我可以编写如下代码:
When using webpack 2(or 3), I could write code like:
const coreStyles = new ExtractTextPlugin('./styles/core.bundle.css');
const componentStyles = new ExtractTextPlugin('./styles/components.bundle.css');
rules: [
{
test: /\.scss$|\.css$/,
include: path.resolve(__dirname, './styles/App.scss'),
use: coreStyles.extract({
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.scss$|\.css$/,
exclude: path.resolve(__dirname, './styles/App.scss'),
use: componentStyles.extract({
use: ['css-loader', 'sass-loader']
})
}
]
结果,我在输出中得到了2个CSS文件.
And as a result, I got 2 css files in output.
如何使用mini-css-extract-plugin
达到相同的目的?根据文档,我只能指定一个文件名:
How can I reach the same with mini-css-extract-plugin
? As according to the docs I can specify only one file name:
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
})
]
谢谢.
推荐答案
此示例还符合SCSS,并且不使用MiniCssExtractPlugin
This Example also complies the SCSS and doesn't use MiniCssExtractPlugin
在Webpack 4.16.5中,我已经设法通过首先安装这两个软件包来使其工作
In Webpack 4.16.5 I have managed to get this to work by first installing these 2 packages
npm install --save-dev file-loader
npm install --save-dev extract-loader
然后在您的webpack.config.js中
Then in your webpack.config.js
//const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var path = require("path");
module.exports = {
entry: ['./blocks.js','./block.editor.scss','./block.style.scss'],
mode: 'production',//change to 'development' for non minified js
output: {
path: path.resolve(__dirname, "dist"),
filename: 'blocks.build.js',
publicPath: "/dist"
},
watch:true,
module: {
rules: [
{
test: /.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].build.css',
context: './',
outputPath: '/',
publicPath: '/dist'
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
],
},
};
这将输出以下结构
- dist
--- block.editor.build.css
--- block.style.build.css
--- blocks.build.js
- blocks.js
- block.editor.scss
- block.style.scss
要最小化CSS安装
npm install --save-dev uglifyjs-webpack-plugin
npm install --save-dev optimize-css-assets-webpack-plugin
添加到webpack.config.js
add to webpack.config.js
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
var path = require("path");
module.exports = {
.....
watch:true,
module: {
rules: [
.....
],
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
};
希望这会有所帮助
这篇关于在Webpack中使用mini-css-extract-plugin输出2个(或更多).css文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!