使用Webpack加载css时如何切换css文件?

yuk*_*uan 16 css gulp webpack

我使用gulp将我的sass文件编译为css文件,并在我的html中引用css文件.项目支持主题切换.例如,我有3个css主题文件:

  • red.css
  • yellow.css
  • blue.css

我现在可以像这样切换主题css:

var styleDom = $('#theme-style');
var newHref = 'styles/themes/' + themeName + '.css';
if (styleDom.attr('href') !== newHref) {
   styleDom.attr('href', newHref);
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用webpack加载css文件.

require('styles/themes/red.css');
Run Code Online (Sandbox Code Playgroud)

它似乎运作良好,但我现在找不到切换主题css文件的方法,有没有人有解决方案?

Kir*_*eck 5

你的方法不需要改变。只需使用Extract Text插件来保存 CSS 文件。您需要创建多个入口点来创建多个 CSS 文件。

或者

更理想的是,(我将采用的方法)使您的 CSS 切换基于不同的 html 或 body 类,只需更改该类即可。它不会增加太多开销,并且在更改主题时会成为更理想的 UX。


juk*_*pff 4

您需要结合使用webpackstyle-loaderfile-loader(第二个示例)并使用require.ensure(第二个示例“动态导入”)来完成此操作:

function switchTheme(name) {
    // Remove the current theme stylesheet
    // Note: it is important that your theme css always is the last
    // <link/> tag within the <head/>
    $('head link[rel="stylesheet"]').last().remove();

    // Since webpack needs all filePaths at build-time
    // you can't dynamically build the filePath
    switch(name) {
        case 'red':
            // With require.ensure, it is possible to tell webpack
            // to only load the module (css) when require is actually called
            return require.ensure([], function () {
                require('style-loader/url!file-loader!styles/themes/red.css');
            });
        case 'yellow':
            return require.ensure([], function () {
                require('style-loader/url!file-loader!styles/themes/yellow.css');
            });
        case 'blue':
            return require.ensure([], function () {
                require('style-loader/url!file-loader!styles/themes/blue.css');
            });
        default:
            throw new Error('Unknown theme "' + name + '"');
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样的调用switchTheme('blue')应该可以解决问题。

webpack.config.js如果您已经配置了文件加载器,您可能需要检查当前的.css