快速入门Sass:Sass中的体系结构

tech2022-12-20  56

The following is a short extract from our recent book, Jump Start Sass, available for free to SitePoint Premium members. Print copies are sold in stores worldwide, or you can order them here. We hope you enjoy this extract and find it useful.

以下是我们最近的书Jump Start Sass的简短摘录, SitePoint Premium会员可以免费获得。 印刷版在世界各地的商店都有出售,您也可以在此处订购 。 我们希望您喜欢此摘录并觉得有用。

Architecture has always been one of the major pain points in CSS development. Without any variables, control directives, macros, or object inheritance, CSS code tends to be long and repetitive-a single ever-growing file. While it’s technically possible to split plain CSS into multiple files that reference each other with @import, the additional HTTP requests make that a poor solution. As you’ve seen, Sass has an answer for every piece of the architecture puzzle-but what’s the best way to put it all together?

架构一直是CSS开发的主要痛点之一。 没有任何变量,控制指令,宏或对象继承,CSS代码往往又长又重复​​-一个不断增长的文件。 从技术上讲,可以将纯CSS拆分为多个文件,这些文件可以使用@import相互引用,但其他HTTP请求使该解决方案不可行。 如您所见,Sass可以解决所有架构难题,但是将其整合在一起的最佳方法是什么?

Ask ten experts, and you’ll receive ten different answers-most of them involving (or aided by) Sass. OOCSS, SMACSS, Atomic Design, ITCSS, and BEM are all popular systems for CSS architecture, but there are many more. If you’re using a front-end framework such as Bootstrap or Foundation, there might be some architectural opinions already built in.

询问十位专家,您将收到十个不同的答案-其中大多数涉及Sass(或由Sass辅助)。 OOCSS , SMACSS , Atomic Design , ITCSS和BEM都是CSS架构的流行系统,但还有更多。 如果您使用的是诸如Bootstrap或Foundation之类的前端框架,则可能已经内置了一些体系结构意见。

These are all solid systems, none of which were designed with your project in mind. CSS architecture is hard, so it’s a mistake to trust any one-size-fits-all solution. There is no “right” answer that works for every team on every project. We’d recommend learning them all, and then mashing together the best parts to create a system that works well for you.

这些都是可靠的系统,没有一个是为您的项目而设计的。 CSS体系结构很难,因此信任任何一种千篇一律的解决方案都是一个错误。 没有“正确”的答案适用于每个项目的每个团队。 我们建议您学习所有这些内容,然后将最好的部分融合在一起,以创建一个适合您的系统。

Let’s start with a broad discussion of the building blocks, and then look at the ways we can fit them together.

让我们从对构建基块的广泛讨论开始,然后看看我们如何将它们组合在一起。

多个文件和文件夹 ( Multiple Files and Folders)

Breaking your code into multiple files is one key advantage to using a preprocessor, and forms the basis of any architecture. With Sass, there’s no harm in breaking your code into the smallest logical units and organizing it into multiple files and folders. We recommend taking full advantage of it.

将代码分为多个文件是使用预处理器的主要优势之一,并且构成任何体系结构的基础。 使用Sass,将代码分解为最小的逻辑单元并将其组织为多个文件和文件夹没有任何害处。 我们建议充分利用它。

Sass has bestowed new power on the CSS @import rule, allowing you to combine Sass and CSS files during compilation so they can be sent to the browser as one single file. This is the only place where Sass has stepped on the toes of an existing CSS directive, so it behaves differently in Sass than it did in CSS.

Sass在CSS @import规则上赋予了新的功能,使您可以在编译期间合并Sass和CSS文件,以便它们可以作为一个文件发送到浏览器。 这是Sass踩到现有CSS指令的唯一位置,因此它在Sass中的行为与在CSS中的行为有所不同。

CSS导入 ( CSS Imports)

As mentioned, the CSS @import directive allows you to reference one CSS file from another. Importing is handled by the browser and requires additional HTTP requests-since the importing file has to be parsed before the @import directive is discovered. If you have a chain of files importing each other, those imports will happen in sequence, blocking the document from rendering until all the CSS has loaded. For that reason, most people avoid CSS imports entirely.

如前所述,CSS @import指令允许您从另一个引用一个CSS文件。 导入由浏览器处理,并且需要其他HTTP请求-因为必须在发现@import指令之前解析导入文件。 如果您有一连串的文件导入,这些导入将按顺序进行,从而阻止文档呈现,直到所有CSS都已加载。 因此,大多数人完全避免CSS导入。

Using CSS imports, you can reference another CSS file using relative or absolute paths, even adding a media query rule for conditional imports. Even though Sass provides different functionality under the same at-rule, there are various cases in which Sass will fall back to the vanilla CSS output, such as when:

使用CSS导入,您可以使用相对或绝对路径引用另一个CSS文件,甚至可以为条件导入添加媒体查询规则。 尽管Sass在相同规则下提供了不同的功能,但在各种情况下Sass都会退回到原始CSS输出,例如:

an imported file has a .css extension

导入的文件的扩展名为.css

a filename begins with http:// or https://

文件名以http://或https://开头

the filename is a url(..) function

文件名是url(..)函数

@import has any media queries

@import有任何媒体查询

The following will compile to standard CSS imports, even in Sass:

以下内容将编译为标准CSS导入,即使在Sass中也是如此:

@import 'relative/styles.css'; @import 'http://absolute.com/styles.css'; @import url('landscape.css') screen and (orientation: landscape);

Sass导入和部分 ( Sass Imports and Partials)

Sass imports look similar to CSS imports, but the imported files are compiled into one single output file, as though their contents (including variables, mixins, functions, and placeholders) were copied and pasted into place before compilation. This type of Sass import will only work on files with .sass or .scss extensions, but you can leave the extension off when importing (as long as there are no similarly named files). In fact, we recommend dropping the extension whenever you can, for simplicity. It’s also possible to import multiple files in one command, or import files into a nested context:

Sass导入看起来类似于CSS导入,但是导入的文件被编译到一个输出文件中,就好像它们的内容(包括变量,mixin,函数和占位符)在编译之前已被复制并粘贴到位。 这种类型的萨斯进口只会与.sass或.scss扩展名的文件的工作,但你可以离开扩展导入时关闭(只要不存在类似命名的文件)。 实际上,为简单起见,我们建议您尽可能删除该扩展名。 也可以在一个命令中导入多个文件,或将文件导入嵌套的上下文中:

// Import an explicit file relative to the current directory @import 'path/to/explicit.scss'; // Import a file with either the .sass or .scss extension @import 'implicit'; // Import multiple files... @import 'path/to/emory.scss', 'miko', 'path/to/gracie'; // Import a file into a nested context... // (imagine the file copied and pasted into this context) .latte { @import 'espresso'; }

The most common use of Sass importing is for partial files—Sass files that are not compiled on their own but are for importing into other files. If you want a Sass file to remain uncompiled until it’s imported, add an underscore (_) to the start of the filename. Sass files that start with _ won’t compile on their own, but can be imported into other files. When importing partials, Sass allows you to leave the _ off, which is similar to leaving off an extension. For example:

Sass导入的最常见用途是用于部分文件-Sass文件不是自己编译的,而是用于导入其他文件的。 如果您希望Sass文件在导入之前保持未编译状态,请在文件名的开头添加下划线( _ )。 以_开头的Sass文件不会自行编译,但可以导入到其他文件中。 导入部分时,Sass允许您关闭_ ,这类似于省略扩展名。 例如:

// _authors.scss .miriam { background: blue; } // jumpstartsass.scss @import 'authors'; // Shorthand for importing '_authors.scss' // jumpstartsass.css (compiled CSS) .miriam { background: blue; }

Running Sass in this directory (sass --update .) compiles jumpstartsass.scss to jumpstartsass.css; however, it won’t create an _authors.css file, since it has a leading underscore.

在此目录( sass --update . )中运行Sass sass --update . jumpstartsass.scss编译为jumpstartsass.css ; 但是,它不会创建_authors.css文件,因为它具有下划线。

Sass partials form the basis of any Sass architecture. Because all Sass imports are handled at compile time and never interrupt the browser, it’s perfectly safe (and recommended) to use as many partials as necessary, compiling them into a single stylesheet for production. For the sake of being organized we recommend breaking out partials liberally, sorting them into folders, and importing them all back into one single master file for compilation. A common Sass directory for a project might look like this:

Sass局部构成任何Sass体系结构的基础。 由于所有Sass导入都是在编译时处理的,并且永远不会中断浏览器,因此,根据需要使用尽可能多的部分并将它们编译为一个样式表以进行生产是绝对安全的(并建议)。 为了有条理,我们建议自由地分解部分,将它们分类到文件夹中,然后将所有部分重新导入到一个主文件中进行编译。 项目的公共Sass目录可能如下所示:

sass/ | |– config/ | |– _colors.scss # Color palettes | |– _webfonts.scss # Webfont information | … # Etc. | |– layout/ | |– _navigation.scss # Navigation | |– _banner.scss # Site Banner | … # Etc. | |– modules/ | |– _calendar.scss # Calendar widget styles | |– _contact.scss # Contact form styles | … # Etc. | |– patterns/ | |– _buttons.scss # Buttons | |– _dropdown.scss # Dropdown | … # Etc. | |- main.scss # The primary Sass file to be compiled

After organizing all your partials, they can be imported into the single primary main.scss file for compilation:

组织完所有部分之后,可以将它们导入到单个主main.scss文件中进行编译:

// Primary Sass File: main.scss @import 'config/colors'; @import 'config/webfonts'; @import 'patterns/buttons'; @import 'patterns/dropdown'; @import 'layout/navigation'; @import 'layout/banner'; @import 'modules/calendar'; @import 'modules/contact';

组成和组织 (Components and Organization)

We’ve advised you to use partials, folders, and imports—but what’s really important is how to use them efficiently. This is where everyone’s opinions differ, and your mileage may vary.

我们建议您使用部分,文件夹和导入-但是真正重要的是如何有效地使用它们。 这是每个人的意见都不同的地方,您的里程可能会有所不同。

Most CSS and Sass organization systems are based on some concept of user interface “components” or discrete pieces that can be put together to form a complete project. Components can be any size or shape, but they should focus on doing one task independently, and in a reusable way. A button, a drop-down, a calendar, and a search form are all examples of components that can be reused at different places across a project. Thinking about your project as a collection of components will help you towards having an organized and maintainable architecture, whether you’re using Sass or plain CSS.

大多数CSS和Sass组织系统都是基于用户界面“组件”或离散组件的某些概念,这些概念可以组合在一起形成一个完整的项目。 组件可以是任何大小或形状,但它们应专注于以可重用的方式独立完成一项任务。 按钮,下拉菜单,日历和搜索表单都是可以在项目中不同位置重用的组件示例。 无论您使用的是Sass还是普通CSS,将您的项目视为组件的集合都将帮助您建立一个有组织且可维护的体系结构。

Because of the way CSS works, the order of your code will also affect its meaning: later code has priority in the cascade over the code before it. Some of the popular branded architectures (the ones you know by name) try to eliminate this feature of the cascade entirely, but I use it as a guide—organizing code from the most general to the most specific—so the priority override makes sense. Code that we want applied generally across the site should come first, growing slowly in specificity and detail as we move towards more unique components and special cases.

由于CSS的工作方式,代码的顺序也会影响其含义:后面的代码在级联中优先于之前的代码。 一些流行的品牌体系结构(您已经知道的名称)试图完全消除级联的这一功能,但是我将其用作指导-从最一般到最具体的组织代码-因此优先级覆盖才有意义。 首先,我们要在整个站点上普遍应用的代码应排在第一位,随着我们朝着更加独特的组件和特殊情况迈进,其特异性和详细性将缓慢增长。

I first learned of this approach from Natalie Downe’s wonderful CSS Systems talk in 2008 before I’d ever used Sass. Her architecture at the time started with elements (h2, ol, ul, and so on) grouped by “type”, followed by classes grouped by the “effect” created, and finally IDs grouped by the “component” they affect. These days it’s common practice to avoid IDs altogether, and break elements into smaller pieces, but the concept remains the same: global defaults first, followed by site-wide patterns and broad layouts, and finally, more specific modules, themes, and overrides.

在我使用Sass之前,我从2008年Natalie Downe精彩的CSS Systems演讲中学到了这种方法。 当时,她的体系结构从按“类型”分组的元素( h2 , ol , ul等)开始,然后是按创建的“效果”分组的类,最后是按它们影响的“组件”分组的ID。 如今,通常的做法是完全避免使用ID,并将元素分成较小的部分,但概念仍然保持不变:首先是全局默认值,然后是整个站点范围的模式和广泛的布局,最后是更具体的模块,主题和替代。

Sass projects include another category of site-wide defaults not found in CSS: code with no output at all—such as variables, functions, and mixin definitions. Many people (myself included) break that code into its own set of partials, to be imported anywhere it might be useful. I have a complete folder just for site-wide Sass helpers and configuration that don’t result in output. Those files act as a single, definitive, and reusable configuration that defines the boundaries of a project. By ensuring your configuration is output-free, you can import it anywhere without worrying about duplicated or unwanted styles.

Sass项目包括CSS中找不到的另一类站点范围默认值:根本没有输出的代码,例如变量,函数和混合定义。 许多人(包括我自己在内)将代码分解成自己的部分代码,然后将其导入可能有用的任何位置。 我有一个仅用于站点范围内的Sass助手和配置的完整文件夹,不会导致输出。 这些文件充当定义项目边界的单一,确定且可重用的配置。 通过确保您的配置没有输出,您可以将其导入任何地方,而不必担心样式重复或多余。

Here are some guidelines for thinking about architecture:

以下是有关架构的一些指导原则:

Break your code into the smallest logical component partials.

将您的代码分成最小的逻辑组件部分。

Organize your partials into grouped folders based on specificity.

根据具体情况将局部文件组织到分组文件夹中。

Import those partials into one master file in order of specificity.

按特定顺序将这些部分导入一个主文件中。

However, many variations do exist on the specific ways people implement those ideas.

但是,人们在实现这些想法的具体方式上确实存在许多变化。

You may also find that a lot of the branded systems developed by and for massive companies with large-scale needs don’t always translate to smaller teams and products. Every project has different requirements, so you should never assume that the best solution for InstaFace or MyPinBook is going to be the best solution for you.

您可能还会发现,由大型公司开发并为有大规模需求的大型公司开发的许多品牌系统并不总是转化为较小的团队和产品。 每个项目都有不同的要求,因此您永远不要以为InstaFace或MyPinBook的最佳解决方案将是您的最佳解决方案。

面向对象CSS(OOCSS) (Object-oriented CSS (OOCSS))

OOCSS is one of the original front-end architectures, and the initial inspiration for adding the @extend directive to Sass. A project from Nicole Sullivan, it places a strong emphasis on finding the right granularity for CSS objects, a theme that comes up in most of the systems we’ll look at here.

OOCSS是原始的前端体系结构之一,也是将@extend指令添加到Sass的最初灵感。 Nicole Sullivan的一个项目,着重强调为CSS对象找到合适的粒度 ,这是我们将在此处讨论的大多数系统中出现的主题。

Sullivan argues that rather than trying to match back-end objects, a CSS object should look for more granular design patterns that might be used across a variety of content types. A prime example is what she calls the media object—a fixed-size media element (such as an image or video) alongside fluid content such as text.

Sullivan认为,CSS对象应该尝试使用更细粒度的设计模式,这些模式可以用于多种内容类型,而不是尝试匹配后端对象。 一个典型的例子是她所说的媒体对象 -固定大小的媒体元素(例如图像或视频)以及诸如文本之类的流畅内容。

Figure 9.1. Facebook media object

图9.1。 Facebook媒体对象

If you look at Facebook, which Sullivan helped refactor, you’ll see one media-object design used across the site to display a wide range of back-end objects—from stories and comments, to notifications, advertisements, and profile details. By defining objects at a granular level, a small amount of CSS can be used to style large swathes of the application.

如果您看一下由Sullivan协助重构的Facebook,您会发现在整个网站上使用了一种媒体对象设计来显示各种各样的后端对象,从故事和评论到通知,广告和个人资料详细信息。 通过在粒度级别上定义对象,可以使用少量CSS来对应用程序的大部分进行样式设置。

At its best, OOCSS is a powerful tool for simplifying CSS and perfecting the performance of large-scale applications. But taken to extremes, the OOCSS approach can leave you with a mess of single-purpose utility classes (such as .padding-left-10px) that couple your HTML and CSS too tightly, and eliminate any maintainability you might get from more semantic code. You’ll have to find the right balance for each project.

最好的情况是,OOCSS是简化CSS和完善大型应用程序性能的强大工具。 但极端的是,OOCSS方法可能会给您带来一堆单一用途的实用程序类(例如.padding-left-10px ),这些类将您HTML和CSS紧密地结合在一起,并消除了您可能从更多语义代码中获得的可维护性。 您必须为每个项目找到合适的平衡。

Whatever else you do, the two main principles of OOCSS are worth keeping in mind (indeed, committing to memory) while you work out your own architecture:

无论您做什么,在设计自己的体系结构时,都应牢记OOCSS的两个主要原则(实际上是致力于内存):

Separate structure and skin. By having multiple design skins (colors, backgrounds, borders, and so on) that you can mix and match with structural objects, it’s possible to achieve more visual variety with less code. In practice, this also means decoupling styles from the base semantics of HTML tags. By styling classes (.primary-header) instead of tags (h2), you have more flexibility to keep HTML meaningful, while applying consistent styles wherever they’re appropriate.

结构与皮肤分开。 通过具有可以与结构对象混合和匹配的多个设计外观(颜色,背景,边框等),可以用更少的代码实现更多的视觉多样性。 实际上,这也意味着将样式与HTML标签的基本语义脱钩。 通过设置类( .primary-header )而不是标签( h2 )的样式,您可以更加灵活地使HTML有意义,同时在适当的地方应用一致的样式。

Separate container and content. OOCSS objects should not be dependent on their location or context, but be reusable and able to fill whatever container they are given. This ensures that an object will look the same in any context, without developers having to guess what a given element or class will do in different situations.

容器和内容分开。 OOCSS对象不应该依赖于它们的位置或上下文,而是可以重用的,并且可以填充给定的任何容器。 这样可以确保对象在任何上下文中看起来都一样,而开发人员不必猜测给定元素或类在不同情况下会做什么。

There is no organizational structure built into OOCSS, but there is a framework available on GitHub that provides a number of common objects, as well as documentation on customizing the framework to your needs.

OOCSS中没有内置组织结构,但是GitHub上有一个框架 ,该框架提供了许多通用对象,以及有关根据需要定制框架的文档。

原子设计 (Atomic Design)

Atomic Design is also driven by questions of granularity. Initially devised by Brad Frost, an atomic project is broken down into five stages: atoms, molecules, organisms, templates, and pages. The idea is to style the stages in order, starting granular and working outwards, with each stage building on the one before.

原子设计也受粒度问题的驱动。 最初由Brad Frost设计的原子项目分为五个阶段:原子,分子,生物,模板和页面。 想法是按顺序对阶段进行样式设置,从粒状开始并向外进行,每个阶段都在之前的阶段构建。

According to Atomic Design, atoms can be abstract information such as color palettes, fonts, and typographic scales; they can also be default styles for tags such as form labels, buttons, and paragraphs. Since I can never remember the scientific terms, I break these two ideas down further and refer to the former as “configuration” or “settings” (having no output on their own), and the latter “base” or “initial” styles (having output).

根据原子设计, 原子可以是抽象信息,例如调色板,字体和印刷比例。 它们也可以是标签的默认样式,例如表单标签,按钮和段落。 由于我永远不记得科学术语,因此我将这两个想法进一步细分,将前者称为“配置”或“设置”(本身没有输出),而后者称为“基础”或“初始”样式(有输出)。

Atoms can be put together to form molecules. Combine an image with a paragraph and button (all atoms), and you have a simple product-listing molecule. Molecules are small components that do one task well. Group a number of these molecules together, and you have an organism (in this case, a gallery of products). Organisms are larger grouped components that form a section of the interface. Your site banner might also be an organism, combining a logo, navigation, and search form. I call these next two stages “patterns” and “components,” but it’s recommended that you work with your team to find terms you all understand clearly.

原子可以放在一起形成分子 。 将图像与段落和按钮(所有原子)结合起来,您将获得一个简单的产品列表分子。 分子是完成一项任务的小组件。 将许多这些分子归为一组,就可以得到一个有机体 (在这种情况下,是一个产品库)。 有机体是组成界面一部分的较大的分组组件。 您的网站横幅也可能是有机体,结合了徽标,导航和搜索表单。 我将接下来的两个阶段称为“模式”和“组件”,但是建议您与团队合作以找到大家都清楚理解的术语。

At this point, the developers of Atomic Design abandon their biochemical analogy, and move to templates. Templates combine the smaller molecules and organisms into actual layout structures. If you run a news site, you might have a list template and a detail template for your articles. Each specific instance of a template is called a page. The home page and archive page of your news site may both use the article-list template, but they have different content. Pages are the most specific combination of all the other stages.

此时,Atomic Design的开发人员放弃了他们的生化类比,转而使用模板 。 模板将较小的分子和有机体组合成实际的布局结构。 如果您运行新闻站点,则可能有文章的列表模板和详细信息模板。 模板的每个特定实例称为页面 。 新闻站点的主页和存档页面可能都使用文章列表模板,但是它们具有不同的内容。 页面是所有其他阶段的最具体组合。

A standard Atomic Design directory will be organized into these five stage-based folders:

标准的Atomic Design目录将组织到这五个基于阶段的文件夹中:

sass/ | |– atoms/ | |– _colors.scss | |– _buttons.scss | … | |– molecules/ | |– _navigation.scss | |– _search.scss | … | |– organisms/ | |– _banner.scss | |– _gallery.scss | … | |– templates/ | |– _list.scss | |– _detail.scss | … | |– pages/ | |– _home.scss | |– _archive.scss | … | |- main.scss

Atomic Design also provides a framework called Pattern Lab. As with OOCSS, avoid confusing the framework with the design system philosophy. You can apply the philosophy anywhere, but the tools are still available if you need them. Frameworks can be a great way to keep code consistent across a large team or project, but always remember that you know your project better than Brad Frost, Nicole Sullivan, or the authors of this book. If there’s a conflict between your needs and the framework you’re using, always put your project first.

原子设计还提供了一个称为Pattern Lab的框架。 与OOCSS一样,避免将框架与设计系统哲学混淆。 您可以在任何地方应用该原理,但是如果需要,这些工具仍然可用。 框架可以是使大型团队或项目中的代码保持一致的一种好方法,但请始终记住,与Brad Frost,Nicole Sullivan或本书的作者相比,您对项目的了解要更好。 如果您的需求和使用的框架之间存在冲突,请始终将项目放在首位。

块,元素,修饰符(BEM) (Block, Element, Modifier (BEM))

BEM is a system developed by the Yandex team. This is a much more extensive system, with its fingers in every aspect of your code—from JSON data structures, to templates, as well as CSS.

BEM是Yandex团队开发的系统。 这是一个范围更广的系统,其手指遍及代码的各个方面-从JSON数据结构,模板到CSS。

The BEM CSS architecture is built around the three ideas in its title. Blocks are components of any size, and can be nested inside each other. The header block might contain a logo block, a navigation block, and a search block. Blocks are reusable, independent, and mobile—so they can be put anywhere on the page, and repeated as often as necessary. Elements are the constituent parts that belong to a specific block. A menu block might be made up of four tab elements. Modifiers are flags on blocks or elements that change their appearance, behavior, or state.

BEM CSS体系结构围绕其标题中的三个构想构建。 块是任何大小的组件,可以相互嵌套。 header块可能包含logo块, navigation块和search块。 块是可重用,独立且可移动的,因此可以将它们放置在页面上的任何位置,并根据需要重复进行。 元素是属于特定块的组成部分。 menu块可能由四个tab元素组成。 修饰符是更改其外观,行为或状态的块或元素上的标志。

The most immediately recognizable aspect of BEM syntax is an intricate naming convention that uses long class names instead of nesting selectors. Rather than targeting .block .element, you would target .block__element. There are variations on the exact syntax, but the formal documentation allow hyphens (-) within a block, element, or modifier name; double underscore (__) between block and element names; and single underscore (_) before a boolean (true/false) modifier, or between a key-value modifier name and its given value.

BEM语法最容易识别的方面是复杂的命名约定,该约定使用长类名而不是嵌套选择器。 而不是定位.block .element ,而是定位.block__element 。 确切的语法有所不同,但是正式文档允许在块,元素或修饰符名称中使用连字符( - )。 块和元素名称之间的双下划线( __ ); 在布尔值(true / false)修饰符之前或键值修饰符名称与其给定值之间加一个下划线( _ )。

Here’s an example straight from the BEM documentation that defines a form block with a _login boolean modifier, a _theme_forest key-value modifier, and two elements:

这是直接来自BEM文档的示例,该示例使用_login布尔值修饰符, _theme_forest键值修饰符和两个元素来定义form块:

<form class="form form_login form_theme_forest"> <input class="form__input"> <input class="form__submit form__submit_disabled"> </form>

A related Sass partial would look like this:

相关的Sass部分看起来像这样:

.form {} .form_theme_forest {} .form_login {} .form__input {} .form__submit {} .form__submit_disabled {}

When BEM naming became popular, people started using the Sass parent selector (&) to automatically generate their BEM class names with less repetition in the code:

当BEM命名变得流行时,人们开始使用Sass父选择器( & )自动生成其BEM类名,并在代码中减少重复:

.form { border: 1px solid black; &__submit { background-color: green; &_disabled { background-color: gray; } } } .form { border: 1px solid black; } .form__submit { background-color: green; } .form__submit_disabled { background-color: gray; }

On the surface, this works great—but it comes at the cost of searchability. If another developer has to find the .form__submit_disabled Sass in order to make a change, searching your Sass files for .form__submit_disabled will fail to return any results.

从表面上看,这很好用,但是却以可搜索性为代价。 如果另一个开发人员必须找到.form__submit_disabled Sass才能进行更改,则在Sass文件中搜索.form__submit_disabled将无法返回任何结果。

The BEM file structure goes beyond CSS and Sass, organizing all assets (JavaScript, CSS, images, and so on) into shared directories by block. Elements and modifiers have their own subdirectories using the same underscore-driven naming conventions:

BEM文件结构超出了CSS和Sass的范围,将所有资产(JavaScript,CSS,图像等)按块组织到共享目录中。 元素和修饰符具有自己的子目录,使用相同的下划线驱动命名约定:

blocks/ |- input/ | |- _type/ | | |- input_type_search.css | | | |- __box/ | | |- input__box.css | | | |- input.css | |- input.js | |- button/ | |- button.css | |- button.js | |- button.png

CSS的可扩展和模块化架构(SMACSS) (Scalable and Modular Architecture for CSS (SMACSS))

SMACSS is a book, workshop, and philosophy by Jonathan Snook. Like Atomic Design, this architecture uses five categories for organizing your CSS, except that they aren’t organized from small to large. Detailed naming patterns are provided to help keep class names consistent. It’s one of the most popular brand-name architectures, and may even be the most comprehensive.

SMACSS是Jonathan Snook的书,讲习班和哲学。 像Atomic Design一样,此体系结构使用五类来组织CSS,不同之处在于它们不是按照大小排列的。 提供了详细的命名模式以帮助保持类名的一致性。 它是最受欢迎的品牌架构之一,甚至可能是最全面的。

The five categories here are base, layout, module, state, and theme. Base rules define the default style of elements, which work similarly to the atoms of Atomic Design. Layout styles are used to break the document into sections that can contain modules, the individual components of a design. State rules define different JavaScript-dependent states for a module or layout; that is, how does it change when it is active or inactive, collapsed or expanded? Most sites have no need for themes, but they can be used to describe multiple style options for the same modules.

这里的五个类别是基础,布局,模块,状态和主题。 基本规则定义了元素的默认样式,这些元素的工作方式类似于“原子设计”的原子。 布局样式用于将文档分为可包含模块 (设计的各个组件)的部分。 状态规则为模块或布局定义了不同JavaScript相关状态; 也就是说,当它处于活动状态或非活动状态,崩溃或扩展时,它将如何变化? 大多数站点不需要主题 ,但是它们可以用于描述同一模块的多个样式选项。

In order to help keep CSS and HTML modules small and mobile, SMACSS pays special attention to what Snook calls the depth of applicability. You may know of the Sass “inception rule,” which states that you should never nest selectors more than three layers deep. That rule helps to keep selectors short (no more than three layers), but the depth of applicability is a bit different. Rather than counting the number of layers, it counts the total DOM distance between the first and last layers.

为了使CSS和HTML模块保持小巧和可移动性,SMACSS特别注意了Snook所说的适用性 。 您可能知道Sass的“初始规则”,该规则指出,嵌套选择器的深度不得超过三层。 该规则有助于使选择器简短(不超过三层),但是适用性的深度有所不同。 它不计算层数,而是计算第一层和最后一层之间的总DOM距离 。

Let’s look at a simple example. Since .mammalia > .primates > .hominidae > .sapiens > .rollsman > .erin has a depth of six, the same basic selector written as .mammalia .sapiens .erin would still have a depth of six. By shortening the selector, we’ve lowered the specificity (a good thing!), but we still have a large depth of applicability. The problem with so much depth is that it makes our CSS more dependent on a particular HTML structure. This is generally solved by keeping our HTML and CSS components small and independent from their containers.

让我们看一个简单的例子。 由于.mammalia > .primates > .hominidae > .sapiens > .rollsman > .erin的深度为6,因此写为.mammalia .sapiens .erin的相同基本选择器的深度仍为6。 通过缩短选择器,我们降低了特异性(这是一件好事!),但适用范围仍然很广。 如此深入的问题在于,它使我们CSS更加依赖于特定HTML结构。 通常可以通过使我们HTML和CSS组件保持较小且独立于其容器来解决此问题。

雨果7-1 (Hugo’s 7-1)

Hugo uses a variation of SMACSS for organizing Sass partials. He calls it the “7-1” system, because it uses seven folders of partials and one master file to pull them all together.

雨果(Hugo)使用SMACSS的变体来组织Sass部分。 他称其为“ 7-1 ”系统,因为该系统使用了七个部分文件夹和一个主文件来将它们全部拉在一起。

The base/ folder contains broad standards across a site—such as a reset, default styles for common HTML tags, common animations, and basic typography. The layout folder includes everything one might need for laying out the structure of a site; for example, boilerplate-like headers, footers, and navigation, as well as your grid system and layout helpers. The components folder is organized into partials by component; the pages folder contains any page-specific styles; and a themes folder holds any theme-related styles (if your project has multiple themes).

base /文件夹包含整个站点的广泛标准,例如重置,常见HTML标签的默认样式,常见动画和基本排版。 布局文件夹包含布局网站结构可能需要的所有内容; 例如,样板样的页眉,页脚和导航,以及网格系统和布局助手。 组件文件夹按组件分为多个部分。 pages文件夹包含任何特定于页面的样式; 一个themes文件夹包含任何与主题相关的样式(如果您的项目有多个主题)。

7-1 also includes an abstracts folder for Sass tools and helpers, which is organized into partials for global variables, functions, mixins, and placeholders. Nothing in this folder should output any CSS if compiled on its own.

7-1还包括一个用于Sass工具和助手的abstracts文件夹,该文件夹被组织为局部变量,用于全局变量,函数,mixin和占位符。 如果自行编译,此文件夹中的任何内容均不应输出任何CSS。

Hugo leaves the possibility of organizing these partials by topic (typography, colors, etc.) rather than type (variables, mixins, functions) for larger projects, but I recommend that across the board. The topic is always the more important distinction in my mind. Placeholders are the only type that I treat in any special way, because their output remains in the location they are defined—while variables, functions, and mixins create output where they are used.

对于较大的项目,Hugo保留了按主题(印刷术,颜色等)而不是类型(变量,mixin,函数)组织这些部分的可能性,但我还是建议您全面使用。 在我看来,主题始终是最重要的区别。 占位符是我以任何特殊方式处理的唯一类型,因为占位符的输出保留在它们定义的位置,而变量,函数和mixins在使用它们的位置创建输出。

Finally, there is a vendors folder for third-party libraries, frameworks, and toolkits such as Normalize, Bootstrap, jQueryUI, FancyButtonsOMG, and so on. These are often kept separate so as to not edit them should they need upgrading later.

最后,还有一个供应商的第三方库,框架,以及诸如正常化,引导,jQueryUI的,FancyButtonsOMG等工具包文件夹中。 它们通常保持分开,以便以后需要升级时不进行编辑。

Put it all together, and you have a Sass directory similar to this:

放在一起,您将拥有一个类似于以下内容的Sass目录:

sass/ | |– base/ | |– _reset.scss # Reset/normalize | |– _typography.scss # Typography rules | … # Etc. | |– components/ | |– _buttons.scss # Buttons | |– _carousel.scss # Carousel | |– _cover.scss # Cover | |– _dropdown.scss # Dropdown | … # Etc. | |– layout/ | |– _navigation.scss # Navigation | |– _grid.scss # Grid system | |– _header.scss # Header | |– _footer.scss # Footer | … # Etc. | |– pages/ | |– _home.scss # Home specific styles | |– _contact.scss # Contact specific styles | … # Etc. | |– themes/ | |– _theme.scss # Default theme | |– _admin.scss # Admin theme | … # Etc. | |– utils/ | |– _variables.scss # Sass Variables | |– _functions.scss # Sass Functions | |– _mixins.scss # Sass Mixins | |– _helpers.scss # Class & placeholders helpers | |– vendors/ | |– _bootstrap.scss # Bootstrap | |– _jquery-ui.scss # jQuery UI | … # Etc. | `– main.scss # Main Sass file

倒三角形CSS(ITCSS) (Inverted Triangle CSS (ITCSS))

ITCSS is a new architecture that is just starting to gain attention. This system from Harry Roberts does a great job defining the problem of CSS architecture and proposing a solution that comes directly out of the CSS language. Rather than working around inheritance and specificity, Roberts puts them at the center of his methodology.

ITCSS是一个刚刚开始引起关注的新体系结构。 哈里·罗伯茨 ( Harry Roberts)的这个系统在定义CSS体系结构问题和提出直接来自CSS语言的解决方案方面做得很好。 罗伯茨没有围绕继承和特殊性开展工作,而是将它们置于他的方法论的中心。

ITCSS organizes all your Sass and CSS based on three metrics: reach, specificity, and explicitness—visualized as an inverted triangle, as shown below:

ITCSS根据三个指标来组织您的所有Sass和CSS:覆盖率,特异性和明确性-可视为倒三角形,如下所示:

Figure 9.2. ITCSS’s inverted triangle

图9.2。 ITCSS的倒三角形

Code should be organized from least to most explicit, starting with general catch-all rules (such as a reset) and moving up to more explicit styles (such as .contact-form). Similarly, code is organized from broadest to narrowest reach—so that styles affecting more HTML come early in the code, and styles with a more localized application come later. Finally, code is organized from lowest to highest specificity, so that later code can always override earlier code.

代码应从最小到最明确地组织,从通用的总体规则(例如重置)开始,然后发展到更明确的样式(例如.contact-form )。 同样,代码是从最广泛的范围到最窄的范围进行组织的,因此影响更多HTML的样式会出现在代码的早期,而本地化的应用程序的样式会在稍后出现。 最后,代码是按照从最低到最高的特异性组织的,因此以后的代码可以始终覆盖以前的代码。

With those metrics in mind, the triangle is broken down into seven layers. Each layer is more specific, explicit, and narrow-reaching than the layer before it, as shown here:

考虑到这些指标,三角形被分为七个层。 每一层都比它之前的层更加具体,明确和狭窄,如下所示:

Figure 9.3. ITCSS’s layers

图9.3。 ITCSS的层

Let’s explore what these layers are in detail. Settings contains global Sass configuration that can be accessed anywhere in the project, such as font sizes, colors, and other project configuration. Tools are global functions and mixins that are helpful across the project and not specific to one component. Generic is the first layer with CSS output of its own, which includes browser resets or normalization, global box-sizing, and any other broad-scoped rules. The elements layer provides default styles for bare HTML elements such as links and paragraphs. It’s similar to the generic layer, except that it provides a more opinionated style.

让我们探究这些层的细节。 设置包含可以在项目中的任何位置访问的全局Sass配置,例如字体大小,颜色和其他项目配置。 工具是全局功能和混入工具 ,它们在整个项目中很有用,而并非特定于一个组件。 通用是具有自己CSS输出的第一层,其中包括浏览器重置或规范化,全局框大小调整以及任何其他广义规则。 elements层为裸HTML元素(例如链接和段落)提供默认样式。 它与通用层相似,不同之处在于它提供了更个性化的样式。

ITCSS objects are similar to OOCSS objects, and are defined in class-based selectors. They define reusable patterns that have a consistent structure no matter what content or cosmetic style is applied, just like the OOCSS media object does. Components are recognizable pieces of an interface, such as a contact form or a product listing. After the initial setup, this is where the majority of a project’s feature-building work takes place. Finally, trump styles can be used to override any other layer. Trumps should be used sparingly, and have as narrow a scope as possible.

ITCSS 对象类似于OOCSS对象,并且在基于类的选择器中定义。 它们定义了可重复使用的模式,无论应用何种内容或修饰样式,其结构都保持一致,就像OOCSS媒体对象一样。 组件是界面的可识别部分,例如联系表或产品列表。 初始设置后,这里就是项目大部分功能构建工作的地方。 最后, 王牌样式可用于覆盖任何其他图层。 特朗普应谨慎使用,范围应尽可能狭窄。

All these layers can be organized into groups of partials. Roberts uses a multilevel file-naming convention (layer-name.partial-name.scss), but we’d recommend using folders instead. The results could look like this:

所有这些层都可以组织成部分局部。 Roberts使用了多层文件命名约定( layer-name.partial-name.scss ),但是我们建议使用文件夹代替。 结果可能如下所示:

@import "settings/global"; @import "settings/colors"; @import "tools/functions"; @import "tools/mixins"; @import "generic/box-sizing"; @import "generic/normalize"; @import "elements/headings"; @import "elements/links"; @import "objects/wrappers"; @import "objects/grid"; @import "components/site-nav"; @import "components/buttons"; @import "components/carousel"; @import "trumps/clearfix"; @import "trumps/utilities"; @import "trumps/ie8";

Miriam的Mix-n-Match (Miriam’s Mix-n-Match)

All that is well and good, but I’m writing this chapter and I think my own architecture is way cooler than anything else we’ve discussed. I’m yet to give it a name, but I will as soon as I decide to tour the universe giving workshops to all my adoring fans. A girl can dream, right?

一切都很好,但是我正在写这一章,我认为我自己的体系结构比我们讨论过的其他任何事物都要酷。 我还没有给它起个名字,但是我一决定去宇宙巡回演出,为所有我的崇拜者们准备工作坊,我就给它起个名字。 一个女孩可以做梦,对吗?

To tell you the truth, I love parts of all these systems—especially ITCSS. I take what works for my team, and make adjustments as needed from one project to the next. For me, it all starts with one rule: follow the cascade. In practice, it looks a lot like ITCSS or Atomic Design (though I find the latter’s biochemical metaphor confusing). I use the same metrics, but break down the categories in slightly different ways.

实话实说,我喜欢所有这些系统的一部分,尤其是ITCSS。 我选择适合自己团队的方法,并根据需要对一个项目进行调整。 对我而言,一切都从一条规则开始:遵循层叠。 实际上,它看起来很像ITCSS或Atomic Design(尽管我发现后者的生化隐喻令人困惑)。 我使用相同的指标,但以略有不同的方式细分类别。

I start with Sass config files that have no output but define all the parameters of a design: colors, fonts, sizes, media-queries, z-indexes, and so on. In my case, it’s almost entirely Sass map variables accessed with a powerful set of functions and mixins I take from project to project: OddBird’s Accoutrement toolkits. Chris Sauvé refers to this approach as a “Sass Central Nervous System”—a consistent system for maintaining and accessing abstract meta-patterns and style guidelines. Ours look something like this:

我从Sass配置文件开始,该文件没有输出,但定义了设计的所有参数:颜色,字体,大小,媒体查询,z索引等。 就我而言,几乎所有的Sass映射变量都可以通过一组功能强大的函数和mixin访问,这些功能和混合我从一个项目到另一个项目: OddBird的Accoutrement工具包。 克里斯·索维(ChrisSauvé)将此方法称为“ Sass中枢神经系统” —一种用于维护和访问抽象元模式和样式准则的一致系统。 我们看起来像这样:

// Accoutrement Config // ------------------- $colors: ( // base color palette 'brand-blue': hsl(195, 100%, 43%), 'brand-red': hsl(0, 100%, 50%), 'brand-pink': hsl(330, 100%, 45%), // color style guide 'background': hsl(0, 0%, 100%), 'text': 'brand-blue' ('shade': 80%), 'action': 'brand-pink', 'focus': 'brand-blue', ); $sizes: ( // base font size 'body-text': 22px, // type sizes 'rhythm': 'body-text' ('minor-third': 2), 'h1': 'body-text' ('minor-third': 3), 'h2': 'body-text' ('minor-third': 2), 'h3': 'body-text' ('minor-third': 1), // other 'corners': 3px, 'page': 30rem, ); $fonts: ( // hosted web font 'body': ( 'name': 'CenturyOldStyle', 'stack': ('Baskerville', 'Palatino', 'Cambria', 'Georgia', 'serif'), 'regular': 'CenturyOldStyle-regular', // webfont file names... 'italic': 'CenturyOldStyle-italic', 'bold': 'CenturyOldStyle-bold', ), // web-safe font stack 'code': ( 'name': 'Consolas', 'stack': ('Menlo', 'Monaco', 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', 'monospace', 'serif') ), );

The toolkit layer is prebuilt, and moves with us from project to project. It includes functions and mixins that put our configuration to work: automating @font-face imports, font-stacks, and typographical rhythms, as well as applying our color palette. It also helps with accessible color contrasts, and automatically generates a visual style guide, so we can see the fonts, colors, and sizes in action.

工具箱层是预先构建的,并且随我们在项目之间移动。 它包含使我们的配置生效的功能和混合函数:自动@font-face导入,字体堆栈和印刷节奏,以及应用我们的调色板。 它还有助于获得可访问的色彩对比,并自动生成视觉样式指南,因此我们可以查看实际使用的字体,颜色和大小。

The next level up is what I call initial styles—resets, web font imports, global defaults, and so on. This is the first layer of code with actual CSS output, and it’s a thin layer. At this point we’re not styling any real patterns, just trying to establish a slightly more beautiful and branded version of the browser defaults.

下一个升级就是我所说的初始样式-重置,Web字体导入,全局默认设置,等等。 这是具有实际CSS输出的第一层代码,并且是一薄层。 在这一点上,我们还没有设置任何实际的样式,只是尝试建立一个稍微更漂亮,更品牌化的浏览器默认设置。

From there I often establish the site layout, adding patterns as needed. The layout partials are similar to Hugo’s, describing all the primary structures of the site. Patterns are design objects, similar to objects in OOCSS and ITCSS. They’re not related to specific content, and might be used anywhere, for anything. For example, buttons and form elements are always some of my first design patterns on a project.

我经常从那里建立站点布局 ,并根据需要添加模式。 布局局部与Hugo相似,描述了站点的所有主要结构。 模式是设计对象,类似于OOCSS和ITCSS中的对象。 它们与特定的内容无关,可以在任何地方用于任何事物。 例如,按钮和表单元素始终是我在项目中的第一个设计模式。

Patterns are abstract, and have no real meaning until they’re used in a component—the actual bits of user interface that appear on a site. Components should follow all the rules described earlier in the chapter: reusable, repeatable, and able to fit in any container. What others systems call page and theme styles are usually defined either as layout templates or components that just happen to be full screen. Any vendor code that I use will come through a packaging system such as npm, and live outside my visible Sass directory:

模式是抽象的,在将它们用于组件之前是没有实际意义的, 组件是出现在站点上的用户界面的实际部分 。 组件应遵循本章前面所述的所有规则:可重用,可重复并且能够放入任何容器中。 其他系统所称呼的页面和主题样式通常定义为布局模板或恰好是全屏的组件。 我使用的任何供应商代码都将通过npm之类的打包系统提供,并位于我可见的Sass目录之外:

sass/ | |– config/ | |– _colors.scss # Color palettes | |– _fonts.scss # Font palettes | … # Etc. | |– initial/ | |– _init.scss # reset/normalization | |– _root.scss # global defaults (mostly :root, html, body) | |– _webfonts.scss # @font-face imports | … # Etc. | |– layout/ | |– _navigation.scss # Navigation | |– _banner.scss # Site Banner | … # Etc. | |– patterns/ | |– _buttons.scss # Buttons | |– _dropdown.scss # Dropdown | … # Etc. | |– components/ | |– _calendar.scss # Calendar widget styles | |– _contact.scss # Contact form styles | … # Etc. | |- main.scss # The primary Sass file to be compiled

Lately, I’ve also included a styleguide folder, and an extra styleguide.scss root Sass file to be compiled separately. These files contain any styleguide-specific components not required by the main app—styles for the color palette, font specimens, and so on.

最近,我还包括了一个styleguide文件夹,以及一个额外的styleguide.scss根Sass文件,可以分别进行编译。 这些文件包含主应用程序不需要的任何特定于样式指南的组件,例如调色板的样式,字体样本等。

Sass中的模块化导入4 (Modular Imports in Sass 4)

As this chapter was being written, the core Sass designers, Natalie Weizenbaum and Chris Eppstein, were working out the details for modular imports, the major new feature that is driving plans for Sass 4. The specifics are still in flux, but the direction they’re going in is exciting, so it’s worth giving you a sneak peak at what they’ve done so far.

在撰写本章时,Sass的核心设计师Natalie Weizenbaum和Chris Eppstein正在研究模块化导入的细节,这是推动Sass 4计划的主要新功能。具体细节仍在不断变化,但是他们的方向是不断变化的进来很令人兴奋,因此值得您一窥他们到目前为止所做的事情。

Modular imports are a move away from the CSS @import syntax towards one that is more powerful and Sass-specific. Where Sass imports currently work as though the entire imported document has been cut and pasted into place, modular imports provide a lot more control for the developer—inspired by best practice in languages such as Python and Dart. It will probably look a little like this:

模块化导入是从CSS @import语法向更强大且特定于Sass的语法的转变。 在Sass导入当前可以正常工作,就好像整个导入文档都被剪切并粘贴到位的情况一样,模块化导入为开发人员提供了更多控制权-受Python和Dart等语言的最佳实践的启发。 它可能看起来像这样:

@use 'path/to/sitepoint/author' as 'miriam'; .sitepoint { @include miriam.write('Jump Start Sass'); -webkit-paycheck: miriam.money('millions'); }

Okay, there may not be a -webkit-paycheck property coming anytime soon, but the rest looks good. So what’s it all about, and why do we need it?

好的,很快就不会有-webkit-paycheck属性了,但是其余的看起来不错。 那么这是怎么回事,为什么我们需要它?

地区性 (Locality)

With the current Sass import system, variables, mixins, and functions live in a global namespace across all files; conflicts are common. It’s impossible to tell by looking at a single Sass file what already exists in that global space; however, with modular imports, nothing is made global unless I explicitly request it. The @use directive will be visible at the top of any importing file, giving me a complete list of available APIs and the power to namespace each however I see fit.

在当前的Sass导入系统中,变量,混合和函数都存在于所有文件的全局命名空间中。 冲突很普遍。 通过查看单个Sass文件无法判断该全局空间中已经存在的内容。 但是,对于模块化导入,除非我明确要求,否则什么都不会成为全局的。 @use指令将在任何导入文件的顶部可见,从而为我提供了可用API的完整列表,并为我提供了合适的命名空间。

If you @use 'example/grids' as 'grid' at the top of a file, and the example/grids.scss file contains a span() mixin and a gutter() function, then they become available in your file as grid.span() and grid.gutter() (the . syntax is still under discussion). The same will be possible with variables, so a $columns variable would be available to as $grid.columns.

如果@use 'example/grids' as 'grid'在文件顶部使用@use 'example/grids' as 'grid' ,并且example / grids.scss文件包含span() mixin和gutter gutter()函数,则它们将在您的文件中作为grid.span()可用grid.span()和grid.gutter() ( .语法仍在讨论中)。 变量也可能如此,因此$columns变量可作为$grid.columns 。

// example/grids.scss @mixin span(…) { … } @function gutter(…) { … } $columns: 12; // my-file.scss @use 'example/grids' as 'grid'; .column { @include grid.span(5 of $grid.columns); margin-bottom: grid.gutter(); }

Sass will default to using the filename as a prefix if none is provided, and also allow you to remove the prefix when you need to. It’s still not clear if prefixing will work with placeholder selectors.

如果未提供文件名,Sass将默认使用文件名作为前缀,并且还允许您在需要时删除该前缀。 前缀是否可以与占位符选择器一起使用还不清楚。

In addition to using a file with or without a given prefix, it might be possible to use an entire file as a mixin, so you can apply the code of that file anywhere you want—even in a nested context. The syntax is still under consideration, but it would make the entire CSS contents (that are not wrapped in a mixin) available to you as a single mixin.

除了使用带有或不带有给定前缀的文件之外,还可以将整个文件用作mixin ,因此即使在嵌套上下文中,也可以在任何位置应用该文件的代码。 语法仍在考虑中,但是它将使整个CSS内容(未包装在mixin中)可以作为单个mixin使用。

封装形式 (Encapsulation)

Modular imports will also give developers—especially library authors—more power over their public API. Currently, when you load a Sass library such as Susy, you gain access to pages and pages of undocumented functions that you’ll never use. I’ve done my best to hide those functions behind long names like _susy-valid-column-math, but they still clutter the global namespace unnecessarily. With encapsulation, you’ll have control over which mixins, functions, variables, and (possibly) placeholders should be made public. Adding - or _ to the start of a name will define it as private.

模块化导入还将为开发人员(尤其是库作者)提供更多使用其公共API的功能。 当前,当您加载诸如Susy之类的Sass库时,您将获得对您将永远不会使用的页面和未记录功能的页面的访问。 我已经尽力将那些函数隐藏在诸如_susy-valid-column-math类的长名称后面,但是它们仍然会不必要地使全局名称空间混乱。 使用封装,您可以控制应公开哪些混合,函数,变量和(可能)占位符。 在名称的开头添加-或_会将其定义为私有。

There is also talk of a @forward directive that would allow authors to pass the API from one module along as part of another. If you wanted to build a Susy flexbox extension, for example, you could tell your extension to forward the Susy API along to your users.

还讨论了@forward指令,该指令允许作者将一个模块的API作为另一个模块的一部分传递。 例如,如果要构建Susy flexbox扩展,可以告诉扩展将Susy API转发给用户。

All of this, of course, is still in the works, and likely to change before it becomes available later in the year. I can’t wait to see how it turns out—in what ways it changes Sass architecture, and helps the Sass ecosystem.

当然,所有这些仍在进行中,并且有可能在今年晚些时候面世之前进行更改。 我等不及要看结果了,它以什么方式改变了Sass的体系结构,并帮助了Sass生态系统。

包装东西 (Wrapping Things Up)

We’ve taken a fairly in-depth look at architecture for your Sass projects. We started off by discussing @import, and seeing how you can use it to split your project code into small logical units and organizing it across multiple files, partials and folders. This forms the basis of any projects architecture. We then moved on to discuss a whole range of architecture options; which you choose will depend on your own projects and preferences. Finally we looked at future options for modular imports that should be in Sass 4.

我们已经对Sass项目的体系结构进行了相当深入的研究。 我们首先讨论@import ,然后看看如何使用它将项目代码拆分为较小的逻辑单元,并在多个文件,局部文件和文件夹中进行组织。 这构成了任何项目体系结构的基础。 然后,我们继续讨论整个体系结构选项。 选择哪种取决于您自己的项目和偏好。 最后,我们研究了应该在Sass 4中使用的模块化导入的未来选项。

翻译自: https://www.sitepoint.com/architecture-in-sass/

最新回复(0)