如何在webpack中预编译scss为单个css文件?

5

使用webpack与React。

阅读了一些文章,但大多数建议为每个组件调用单独的scss文件。 但我希望像使用grunt / gulp一样将所有css预编译到整个应用程序的单个文件中。

enter image description here

2个回答

4
您可以使用负责编译所有CSS文件并将它们捆绑在一个index.css文件中的webpack-text-extract-pluggin
此外,请注意您还需要安装sass-loader来编译SCSS。
在webpack配置中:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
config = {
    ..., 
    plugins: [
        ...,
        new ExtractTextPlugin('index.css')
    ],
    module: {
        loaders: [
            ...
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract('style','css')
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('style', 'css!sass')
            }
        ]
    }
}

在 index.html 文件中:
<link rel="stylesheet" type="text/css" href="/index.css">

在任何通过webpack的Javascript文件中:
require("./styles/my-custom-file.scss");

3
你可以查看extract-text-webpack-plugin。在webpack.config.js中引用后:
var ExtractTextPlugin = require("extract-text-webpack-plugin");

你可以将你的Sass加载器重写为以下内容:
module: {
    loaders: [
        {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
        {test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css', 'sass')}
    ]
},
plugins: [
    new ExtractTextPlugin('bundle.css')
]

如需更多选项和使用方法,请查看上面的链接。


感谢 @erik-Martijn。 - scazzy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接