这里是 Webpack 业余爱好者...我正在尝试合并一个 theme.scss
文件,按照 here 指定的说明来自定义 React Toolbox 使用的主题。 ,即:
If you are using Webpack as module bundler, you are probably using sass-loader as well. What we want to do is to prepend to each SASS file compilation a bunch of variables to override and this can be done with the data option. For example:
sassLoader: { data: '@import "' + path.resolve(__dirname, 'theme/_theme.scss') + '";' }
In this case we have are prepending the theme import to each SASS compilation so the primary color will be changed in every single stylesheet.
我在使用当前的 webpack 配置实现此指令时遇到问题,如下所示:
const webpack = require('webpack');
const path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.join(__dirname, 'client'),
entry: [
'./main.js',
],
output: {
path: path.join(__dirname, 'www'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
'babel-loader',
],
},
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: "[name]--[local]--[hash:base64:8]"
}
},
"postcss-loader" // has separate config, see postcss.config.js nearby
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader', options: {
sourceMap: true,
data: '@import "' + path.resolve(__dirname, 'theme.scss') + '";'
}
},
'postcss-loader',
{
loader: 'sass-loader', options: {
sourceMap: true,
data: '@import "' + path.resolve(__dirname, 'theme.scss') + '";'
}
},
],
})
}
]
},
plugins: [
new ExtractTextPlugin({
filename: 'style.css',
allChunks: true
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
},
};
我没有收到错误,但似乎 data
选项被完全忽略,因为我的文件未导入。
这是我的theme.scss
文件(位于client/theme.scss
):
@import "~react-toolbox/lib/colors";
$color-primary: $palette-red-500;
$color-primary-dark: $palette-red-700;
body {
background-color: black; //testing
}
我觉得我一定在这里做了一些愚蠢的事情,但我快把自己逼疯了。我尝试弄乱 theme.scss
文件的路径(将 data
属性更改为 data: '@import "' + path.resolve(__dirname, 'client/theme.scss') + '";'
) 但这没有什么区别。我很惊讶我没有收到某种错误。
有什么建议吗?
最佳答案
以下配置对我有用
{
test: /\.scss$/,
include: /client/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
loader: [
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: false,
localIdentName: '[name]_[local]_[hash:base64:5]',
},
},
'postcss-loader',
{
loader: 'sass-loader',
query: {
sourceMap: false,
data: `@import "${path.resolve(__dirname, 'client/_theme.scss')}";`
}
}
],
}),
},
和client/_theme.scss
文件
@import "react-toolbox/lib/colors.css";
$color-primary: var(--palette-blue-500);
$color-primary-dark: var(--palette-blue-700);
我检查了 react-toolbox
库中的 colors.css
文件并使用了相同的变量名称。即 --palette-blue-500
,而不是 $palette-blue-500
。
关于reactjs - 使用 webpack 为 SCSS 添加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345881/