gpt4 book ai didi

css - 网页包 4 : mini-css-extract-plugin + sass-loader + splitChunks

转载 作者:技术小花猫 更新时间:2023-10-29 10:17:47 28 4
gpt4 key购买 nike

我有以下示例配置以将 mini-css-extract-plugin 与 Webpack 4 结合使用:

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 没有。

一般来说,每次导入 .css 文件都会被 splitChunks 选项处理(只有在名称中指定扩展名 css 时),而 sass 导入则不会。

我有一个具有多个 sass 入口点和许多 sass 组件 @import 的元素,我想创建一个包含共享 sass 模块的公共(public)包。

最佳答案

我正在我的 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/"
},

edit If you are interested in code splitting, Webpack 4 can do this "out of the box" for you. This will split .js and as well .css -files for you in case you use dynamic imports.

optimization: {
splitChunks: {
chunks: 'all'
}
}

如果您另一方面只想将您的 .css 合并到一个文件中,您可以按如下方式添加。

optimization: {
splitChunks: {
chunks: 'all'
cacheGroups: {
styles: {
name: 'styles',
test: /\.s?css$/,
chunks: 'all',
minChunks: 1,
reuseExistingChunk: true,
enforce: true,
},
}
},
}

关于css - 网页包 4 : mini-css-extract-plugin + sass-loader + splitChunks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410921/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com