javascript 使用 RequireJS 模块化 CSS 样式表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14956014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:00:47  来源:igfitidea点击:

Modulizing CSS Stylesheets with RequireJS

javascripthtmlcsstemplatesrequirejs

提问by Flosculus

I have created a template like so:

我创建了一个这样的模板:

// template.tpl
<div>
    <input id="an_input"></input>
</div>

and some CSS:

和一些 CSS:

// stylesheet.css
input {
    background: #000000;
}

Finally this is a slimmed down module:

最后,这是一个精简的模块:

define([
    'jquery',
    'text!template.tpl',
    'text!styleshet.css'
], function($, html, css){      
    var view = $('#sample_div');
    view.append($(html));

    var regex = /^([^\s\}])/gm;

    var styles = css.replace(regex, '#'+view.attr('id')+' ');
    var style = $('<style>\n'+styles+'\n</style>');
    view.prepend(style);
});

What is essentially happening, is the template is being loaded and put into the #sample_div. Shortly after the CSS file is being loaded as text, then every item is prefixed with the ID of the view.

本质上发生的是模板正在加载并放入#sample_div. 在 CSS 文件作为文本加载后不久,每个项目都以视图的 ID 为前缀。

Once the CSS is prefixed, the style tag is created and placed inside the view.

一旦 CSS 被加上前缀,样式标签就会被创建并放置在视图中。

Now, this works perfectly, OK it isn't pretty, nor does it leave much margin for error. However I wrote this code to help demonstrate what I need.

现在,这完美地工作,好吧,它不漂亮,也没有留下太多的错误余地。但是我写了这段代码来帮助演示我需要什么。

I need to be able to load templates with view specific stylesheets, where the styles in the sheet will only ever apply to the view and will only override global styles.

我需要能够使用特定于视图的样式表加载模板,其中表中的样式将只应用于视图并且只会覆盖全局样式。

The problem with the above example is that it is a hack, a regex against the CSS, and the building of a new style tag, this is not how I want to do it. I have been looking into javascript CSS parsers for a cleaner solution, and although JSCSSP caught my eye, it put to many functions into the global namespace, and jquery.parsecss only seems to work with styles already within the document.

上面例子的问题在于它是一个 hack,一个针对 CSS 的正则表达式,以及一个新样式标签的构建,这不是我想要的方式。我一直在寻找 javascript CSS 解析器以获得更清晰的解决方案,虽然 JSCSSP 引起了我的注意,但它把许多函数放入了全局命名空间,而 jquery.parsecss 似乎只适用于文档中已有的样式。

Does anyone have any experience with what I am trying to achieve?

有没有人对我想要实现的目标有任何经验?

采纳答案by ddotsenko

Most loaders out there have CSS plugins that handle the insertion for you:

大多数加载器都有 CSS 插件来为你处理插入:

RequireJS CSS plugin https://github.com/tyt2y3/requirejs-css-plugin

RequireJS CSS 插件 https://github.com/tyt2y3/requirejs-css-plugin

CurlJS CSS plugin is bundled with the main distribution: https://github.com/cujojs/curl/tree/master/dist

CurlJS CSS 插件与主要发行版捆绑在一起:https: //github.com/cujojs/curl/tree/master/dist