Webpack: SCSS to CSS file



如何获取我的 SCSS 源代码并将其编译成(奖励:缩小的(CSS 文件?

阅读文档和搜索网络可以清楚地看到的一件事是,每个人似乎都在煮自己的汤,对于这种常见的任务,没有标准/推荐的方法。

这就是我在这里所做的

首先,我将在 webpack 中使用此设置将我的 scss 转换为 css 文件

module: {
rules: [{
test: /.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
}
]
}

然后我使用 webpack-shell-plugin 运行 postcss 命令来缩小 css 文件。(奖励我还使用压缩插件添加 gzip 以将 css 转换为 gzip(

plugins: [
new CompressionPlugin({
test: /.(js|css)/
}),
new WebpackShellPlugin({
onBuildStart: ['echo "Starting postcss command"'],
onBuildEnd: ['postcss --dir wwwroot/dist wwwroot/dist/*.css']
})
],

下面是一个对我有用的最小示例:

package.json:

{
…
"devDependencies": {
"css-loader": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"node-sass": "^4.12.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"sass-loader": "^8.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9"
}
}

webpack.config.js:

const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
…
module: {
rules: [
{ // CSS assets remaining in the pipeline (e.g. frameworks)
test: /.css$/,
use: [
"style-loader", // or e.g. "vue-style-loader" etc. (optional)
MiniCssExtractPlugin.loader,
"css-loader"
]
},
{ // SCSS
test: /.scss$/,
use: [
"style-loader" // (optional)
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
},
// Plugins
plugins: [
new MiniCssExtractPlugin({
filename: "./css/my-style.css" // relative to `output.path` by default
}),
new OptimizeCssAssetsPlugin() // construction suffices, no additional calls needed
]
};

node-sass模块已经输出了缩小的 CSS,所以如果你知道你的项目中不会遇到任何原始 CSS,你可以摆脱OptimizeCssAssetsPlugin

最新更新