【问题标题】:How to switch css file when using Webpack to load css?使用Webpack加载css时如何切换css文件?
【发布时间】:2016-07-26 08:23:02
【问题描述】:

我使用 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);
}

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

require('styles/themes/red.css');

好像效果不错,但是我现在找不到切换主题css文件的方法,有没有人有解决办法?

【问题讨论】:

  • 您是否需要切换运行时,或者一旦包含到构建中结果将保持不变?
  • @bebraw,我需要在 rumtime 切换 css。
  • 一旦您需要超越典型的样板配置,Webpack 将毫无用处。几天来,我一直在为同样的概念苦苦挣扎。
  • 您可以在这个问题中检查更改 css 主题:stackoverflow.com/questions/38270362/… 有静态和分块版 css 的解决方案。

标签: css gulp webpack


【解决方案1】:

您需要使用combination of webpacks style-loader and file-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 + '"');
    }
}

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

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

【讨论】:

    【解决方案2】:

    您的方法不需要改变。只需使用 Extract Text 插件来保存 CSS 文件。您需要使用 multiple entry points 来创建多个 CSS 文件。

    更理想的是,(我会采用的方法)使您的 CSS 切换基于不同的 html 或 body 类,然后更改类。它不会增加太多开销,并且在更改主题时会是一个更理想的用户体验。

    【讨论】:

    • 更简单的方法。但是,如果您对自己的样式和线条数量过于具体,则管理起来会更加困难。
    • 您的第二个链接已失效。错误是:The webpack 1.x documentation was deleted.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2016-07-12
    • 2019-09-21
    • 2019-03-04
    相关资源
    最近更新 更多