我使用以下示例配置在webpack 4中使用mini-css-extract-plugin:
entry: {
a: ['./js/a.js', './scss/a.scss'],
b: ['./js/b.js', './scss/b.scss']
},
module: {
rules: [
[...],
{
test: /\.(css|sass|scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 2,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: () => [
require('autoprefixer')
],
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
js: {
test: /\.js$/,
name: "commons",
chunks: "all",
minChunks: 7,
},
css: {
test: /\.(css|sass|scss)$/,
name: "commons",
chunks: "all",
minChunks: 2,
}
}
}
},
plugins: [
new MiniCssExtractPlugin({
filename: "dist/[name].css",
}),
]
以下sass文件:
// a.scss
@import 'libA.scss';
@import 'libB.css';
[...]
// b.scss
@import 'libA.scss';
@import 'libB.css';
[...]
当我运行webpack libB.css
插入commons.css
捆绑时libA.scss
而不是。{/ p>
通常,.css
文件的每个导入都由splitChunks选项处理(仅当名称中指定了扩展名css
时),而不导入sass。
我有一个包含多个sass入口点的项目和许多sass组件的@import,我想创建一个带有共享sass模块的公共包。
答案 0 :(得分:14)
我在我的Webpack 4配置中做这样的事情。
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module: {
rules: [ {
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true,
importLoader: 2
}
},
"sass-loader"
]}
]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "style.css",
chunkFilename: "[name].css"
]
我还将“output.publicPath”-configuration对象指向我的构建目录,例如 - >
output: {
filename: "[name]-min.js",
path: path.resolve(__dirname, "dist"),
publicPath: "/static/react/dist/"
},
编辑如果您对代码拆分感兴趣,Webpack 4可以为您“开箱即用”。如果您使用动态导入,这将为您分割
.js
和.css
- 文件。
optimization: {
splitChunks: {
chunks: 'all'
}
}
如果您的另一只手想将您的.css
合并到一个文件中,您可以添加如下。
optimization: {
splitChunks: {
chunks: 'all'
cacheGroups: {
styles: {
name: 'styles',
test: /\.s?css$/,
chunks: 'all',
minChunks: 1,
reuseExistingChunk: true,
enforce: true,
},
}
},
}