我尝试使用webpack 2从相同的SCSS源生成2个不同的CSS文件,以便拥有备用样式表而无需复制代码。我已经通过评论一个单独成功生成了两个工作表,但无法弄清楚如何同时生成它们。我的webpack配置(缩短相关性)是:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
const ExtractLightCss = new ExtractTextPlugin("app-light.css")
const ExtractDarkCss = new ExtractTextPlugin("app-dark.css")
module.exports = {
...
module: {
rules: [
{
test: /\.scss?$/,
use: ExtractLightCss.extract({ fallback: "style-loader", use: ["css-loader", {loader: "sass-loader", options: {data: "$light: true;"}} ]})
},
{
test: /\.scss$/,
use: ExtractDarkCss.extract({ fallback: "style-loader", use: ["css-loader", {loader: "sass-loader", options: {data: "$light: false;"}} ]})
},
...
]
},
plugins: [
ExtractLightCss,
ExtractDarkCss
]
};
如果我尝试在此配置上运行webpack,我会收到错误
ERROR in ./~/css-loader!./~/sass-loader?{"data":"$light: true;"}!./~/extract-text-webpack-plugin/loader.js?{"id":2,"omit":1,"remove":true}!./~/style-loader!./~/css-loader!./~/sass-loader?{"data":"$light: false;"}!./styles/[filename].scss
这使得它看起来像是同时运行两组规则,而不是运行另一套规则。
有没有办法做到这一点?
答案 0 :(得分:0)
我做了进一步的研究,似乎没有直接的方法来做到这一点(我发现https://survivejs.com/webpack/foreword/是一个很好的资源)。但是我确实找到了解决办法。我使用了'composing-configuration'以防止重复的方式创建我的模块规则,然后导出两个配置,以便webpack同时构建它们。一个简单的例子是:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const merge = require('webpack-merge');
const deploymentSass = (light) => {
return {
module: {
rules: [
{
test: /\.scss?$/,
use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", {
loader: "sass-loader",
options: {
data: light ? "$light: true;" : "$light: false;",
}} ]}),
},
],
},
plugins: [
new ExtractTextPlugin(`app-${light ? 'light' : 'dark'}.css`),
],
};
};
const lightTheme = merge(qaConfig,
deploymentSass(true));
const darkTheme = merge(qaConfig,
deploymentSass(false));
module.exports = [
lightTheme,
darkTheme,
]
这不是一个完美的解决方案,因为它涉及2个版本,但它允许我生成两个样式表而无需重复代码