动态scss变量流星

时间:2014-04-15 18:29:30

标签: meteor sass

我有一个scss变量$ tint-color,用于大约100个地方。

一旦用户登录,我想根据他们的个人资料加载颜色并替换$ tint-color的所有用法。

到目前为止,我发现了两个非理想的解决方案:

1)Iterate through all elements并替换相关属性。

我不断产生新的元素 - 所以这需要反复发生。

2)创建一个覆盖每个元素的覆盖样式表。

这将需要大量重复的代码。

有更好/更简单的方法吗?我曾考虑过在scss中为一个元素添加一个类,但我不确定这是否可行。感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我现在正在做的是在加载配置文件后加载主题css文件。

在服务器上,我公开了iron-router路由,该路由动态替换任何颜色,并返回主题css。

问题是我没有替换scss变量,而是替换任何颜色的出现。这是因为执行代码时,.scss文件已经捆绑到服务器上的.css文件中。

// return a theme based on the tintColor parameter
this.route('theme', {
    where: 'server',

    action: function () {
        var files = fs.readdirSync('../client');

        // find the css file (not the .map file)
        var cssFile = _(files).find(function (fileName) {
            return fileName.indexOf('.css') > 0 && fileName.indexOf('.map') < 0;
        });

        var style = fs.readFileSync('../client/' + cssFile, 'utf8');

        // remove comments (cannot have them for minification)
        style = style.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm, '');

        // replace the default tint-color with the dynamic color
        style = style.replace(/8cb850/g, this.params.tintColor);

        // minify css
        if (Settings.isProduction()) {
            // from the minifiers package
            style = CssTools.minifyCss(style);
        }

        this.response.writeHead(200, {'Content-Type': 'text/css'});
        this.response.end(style);
    }
});

更新:我用scss变量生成它。

Theme.compile = function (tintColor) {
    var dirName = path.dirname(styleFile);

    var styles = fs.readFileSync(styleFile, 'utf8');

    //replace default theme with dynamic theme
    var theme = '$tint-color: #' + tintColor + ';' + '\n';
    styles = styles.replace('@import "app/theme.scssimport";', theme);

    var options = {
        data: styles,
        sourceComments: 'map',
        includePaths: [dirName] // for @import
    };

    var css = sass.renderSync(options);

    // minify css
    if (Settings.isProduction()) {
        // remove comments -- cannot have them for minification
        css = css.replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm, '');

        // Use CssTools from the minifiers package
        css = CssTools.minifyCss(css);
    }

    return css;
};

如果这样做,请确保将scss文件作为资源添加到包example here中。

答案 1 :(得分:1)

在原始css中设置基本的$ tint-color。

然后使用meteor以所选的用户色调发送内联CSS。

示例:

.tint {
  background-color: USER-TINT;
  color: USER-TINT;
}

通过这种方式,您可以缓存原始css文件并节省传输负载!