如何使用 webpack 提取多个主题样式表? [英] How to extract multiple theme stylesheets with webpack?
问题描述
我正在尝试使 React 应用程序主题化.目前主题仅由定义不同标题颜色等的不同 Sass 变量集组成.
I am trying to make a React app themeable. For now themes only consist of different sets of Sass variables which define different header colors, etc.
根据我目前的理解,ExtractTextPlugin
似乎是我最好的选择,因为我不希望我的样式被内联,而是每个主题都有单独的文件.
From my current understanding the ExtractTextPlugin
seems to be my best bet as I don't want my styles to be inlined and rather have separate files per theme.
所以我创建了两个主题:
So I created two themes:
src/scss/themes/theme-a.scss
src/scss/themes/theme-b.scss
主题导入基本布局和常用样式并覆盖相关变量.
The themes import the basic layout and common styles and override the relevant variables.
但我设法让 webpack 创建单独的 css 文件的唯一方法这两个主题是为每个主题创建不同的入口点我的 webpack.prod.config
:
But the only way I managed to make webpack create separate css files
for both themes was to create distinct entry points for each theme in
my webpack.prod.config
:
entry: {
app: './src/js/init.js',
theme-a: './src/scss/themes/theme-a.scss',
theme-b: './src/scss/themes/theme-b.scss'
},
但是为每个添加的新主题添加一个新的入口点感觉是错误的,我认为一定有更好的方法吗?
But adding a new entry point for every new theme that gets added feels wrong and I figure there must be a better way?
推荐答案
这是您的解决方案:
npm i --save-dev file-loader
在 loaders
部分,添加:
{
test: /themes\/.+\.scss$/,
loader: "file-loader?name=./compiled-themes/css/[name].css!css!sass"
},
可能会有更多的 scss 文件,如果是这样,那么肯定会有另一个部分像往常一样捆绑它们,但会跳过主题:
There may be more scss files, if so there must be another section which bundles them as usual, but skips the themes:
{
test: /\.scss$/,
exclude: /themes\/.+\.scss$/,
loader: "css!sass"
},
文件加载器按文件名、散列和扩展名写入文件,因此您可以保留名称.
The file loader writes files by filename, hash and extension so you are able to preserve the name.
注意 name=./compiled-themes/css/[name].css
部分,其中 []
变量被替换.
Note the name=./compiled-themes/css/[name].css
part, where []
vars are substituted.
https://github.com/webpack/file-loader
这篇关于如何使用 webpack 提取多个主题样式表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!