是否可以使用 @import 在 sass 中导入整个目录?

发布于 2024-10-14 05:35:08 字数 396 浏览 4 评论 0原文

我正在使用 SASS 部分来模块化我的样式表,如下所示:

@import partials/header
@import partials/viewport
@import partials/footer
@import partials/forms
@import partials/list_container
@import partials/info_container
@import partials/notifications
@import partials/queues

有什么方法可以包含整个部分目录(它是一个充满 SASS 部分的目录),例如 @import compass 或其他内容?

I'm modularizing my stylesheets with SASS partials like so:

@import partials/header
@import partials/viewport
@import partials/footer
@import partials/forms
@import partials/list_container
@import partials/info_container
@import partials/notifications
@import partials/queues

Is there any way to include the whole partials directory(it's a directory full of SASS-partials) like @import compass or something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

失与倦" 2024-10-21 05:35:09

丹尼斯·贝斯特 (Dennis Best) 接受的答案指出,“否则,加载顺序是而且应该是无关紧要的......如果我们做得正确的话。”这是完全错误的。
如果你做得正确,你可以利用 css 顺序来帮助你减少特殊性并保持 css 简单和干净。

我组织导入的方法是在目录中添加一个 _all.scss 文件,并按正确的顺序导入其中的所有相关文件。
这样,我的主导入文件将变得简单干净,如下所示:

// Import all scss in the project

// Utilities, mixins and placeholders
@import 'utils/_all';

// Styles
@import 'components/_all';
@import 'modules/_all';
@import 'templates/_all';

如果需要,您也可以对子目录执行此操作,但我认为 css 文件的结构不应该太深。

虽然我使用这种方法,但我仍然认为 sass 中应该存在 glob 导入,适用于顺序不重要的情况,例如 mixins 甚至动画的目录。

The accepted answer by Dennis Best states that "Otherwise, load order is and should be irrelevant... if we are doing things properly." This is simply incorrect.
If you are doing things properly, you make use of the css order to help you reduce specificity and keeping you css simple and clean.

What I do to organize imports is adding an _all.scss file in a directory, where I import all the relevant files in it, in the correct order.
This way, my main import file will be simple and clean, like this:

// Import all scss in the project

// Utilities, mixins and placeholders
@import 'utils/_all';

// Styles
@import 'components/_all';
@import 'modules/_all';
@import 'templates/_all';

You could do this for sub-directories as well, if you need, but I don't think the structure of your css files should be too deep.

Though I use this approach, I still think a glob import should exist in sass, for situations where order does not matter, like a directory of mixins or even animations.

亢潮 2024-10-21 05:35:09

您可以生成自动导入所有内容的 SASS 文件,我使用这个 Gulp 任务:

concatFilenames = require('gulp-concat-filenames')

let concatFilenamesOptions = {
    root: './',
    prepend: "@import '",
    append: "'"
}
gulp.task('sass-import', () => {
    gulp.src(path_src_sass)
        .pipe(concatFilenames('app.sass', concatFilenamesOptions))
        .pipe(gulp.dest('./build'))
})

您还可以通过对文件夹进行排序来控制导入顺序,如下所示:

path_src_sass = [
    './style/**/*.sass', // mixins, variables - import first
    './components/**/*.sass', // singule components
    './pages/**/*.sass' // higher-level templates that could override components settings if necessary
]

You can generate SASS file which imports everything automatically, I use this Gulp task:

concatFilenames = require('gulp-concat-filenames')

let concatFilenamesOptions = {
    root: './',
    prepend: "@import '",
    append: "'"
}
gulp.task('sass-import', () => {
    gulp.src(path_src_sass)
        .pipe(concatFilenames('app.sass', concatFilenamesOptions))
        .pipe(gulp.dest('./build'))
})

You can also control importing order by ordering the folders like this:

path_src_sass = [
    './style/**/*.sass', // mixins, variables - import first
    './components/**/*.sass', // singule components
    './pages/**/*.sass' // higher-level templates that could override components settings if necessary
]
怀中猫帐中妖 2024-10-21 05:35:09

这对我来说效果很好

@import 'folder/*';

this worked fine for me

@import 'folder/*';
动次打次papapa 2024-10-21 05:35:09

通过定义要导入的文件,可以使用所有文件夹的通用定义。

因此,@import "style/*" 将编译 style 文件夹中的所有文件。

有关 Sass 中导入功能的更多信息,您可以在此处找到。

With defining the file to import it's possible to use all folders common definitions.

So, @import "style/*" will compile all the files in the style folder.

More about import feature in Sass you can find here.

你的呼吸 2024-10-21 05:35:08

如果您在 Rails 项目中使用 Sass,则 sass-rails gem, https://github.com/rails /sass-rails,具有 glob 导入功能。

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

为了回答另一个答案中的问题“如果导入一个目录,如何确定导入顺序?这不可能不引入一些新的复杂程度。”

有些人认为将文件组织到目录中可以降低复杂性。

我的组织的项目是一个相当复杂的应用程序。 17个目录下有119个Sass文件。这些大致对应于我们的视图,主要用于调整,繁重的工作由我们的自定义框架处理。对我来说,几行导入的目录比 119 行导入的文件名稍微简单一些。

为了解决加载顺序,我们将需要首先加载的文件(mixins、变量等)放置在早期加载目录中。否则,加载顺序应该是无关紧要的......如果我们做得正确的话。

If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."

Some would argue that organizing your files into directories can REDUCE complexity.

My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.

To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.

无悔心 2024-10-21 05:35:08

此功能永远不会成为 Sass 的一部分。主要原因之一是进口订单。在 CSS 中,最后导入的文件可以覆盖之前声明的样式。如果导入目录,如何确定导入顺序?没有办法不引入一些新的复杂性。通过保留导入列表(如您在示例中所做的那样),您可以明确导入顺序。如果您希望能够自信地覆盖在另一个文件中定义的样式或在一个文件中编写 mixin 并在另一个文件中使用它们,这一点至关重要。

如需更深入的讨论,请在此处查看此已关闭的功能请求

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

眼趣 2024-10-21 05:35:08

我在 partials 的同一目录中创建了一个名为 __partials__.scss 的文件

|- __partials__.scss
|- /partials
   |- __header__.scss
   |- __viewport__.scss
   |- ....

__partials__.scss 中,我写了这些:

@import "partials/header";
@import "partials/viewport";
@import "partials/footer";
@import "partials/forms";
....

所以,当我想要导入时整个partials,只需编写@import "partials"。如果我想导入其中任何一个,我也可以编写@import "partials/header"

I create a file named __partials__.scss in the same directory of partials

|- __partials__.scss
|- /partials
   |- __header__.scss
   |- __viewport__.scss
   |- ....

In __partials__.scss, I wrote these:

@import "partials/header";
@import "partials/viewport";
@import "partials/footer";
@import "partials/forms";
....

So, when I want import the whole partials, just write @import "partials". If I want import any of them, I can also write @import "partials/header".

乙白 2024-10-21 05:35:08

这可能是一个老问题,但在 2020 年仍然相关,所以我可能会发布一些更新。
自 19 年 10 月更新以来,我们通常应该使用 @use 而不是 @import,但这只是一个备注。这个问题的解决方案是使用索引文件来简化包括整个文件夹的过程。下面的例子。

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}

// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}

// foundation/_index.scss
@use 'code';
@use 'lists';

// style.scss
@use 'foundation';

https://sass-lang.com/documentation/at-rules/use #索引文件

It might be an old question, but still relevant in 2020, so I might post some update.
Since Octobers'19 update we generally should use @use instead of @import, but that's only a remark. Solution to this question is use index files to simplify including whole folders. Example below.

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}

// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}

// foundation/_index.scss
@use 'code';
@use 'lists';

// style.scss
@use 'foundation';

https://sass-lang.com/documentation/at-rules/use#index-files

苦行僧 2024-10-21 05:35:08

您可以使用一些解决方法,将 sass 文件放置在您想要导入的文件夹中,并导入该文件中的所有文件,如下所示:

file path:main/current/_current.scss

@import "placeholders";
@import "colors";

在下一个目录级别文件中,您只需使用 import 导入从该目录导入所有文件的文件:

file path:main/main.scss

@import "EricMeyerResetCSSv20";
@导入“clearfix”;
@import "current";

这样你就有相同数量的文件,就像你导入整个目录一样。请注意顺序,最后出现的文件将覆盖匹配的阶梯。

You could use a bit of workaround by placing a sass file in folder what you would like to import and import all files in that file like this:

file path:main/current/_current.scss

@import "placeholders";
@import "colors";

and in next dir level file you just use import for file what imported all files from that dir:

file path:main/main.scss

@import "EricMeyerResetCSSv20";
@import "clearfix";
@import "current";

That way you have same number of files, like you are importing the whole dir. Beware of order, file that comes last will override the matching stiles.

嘿咻 2024-10-21 05:35:08

您可能想保留源顺序,那么您可以使用它。

@import
  'foo',
  'bar';

我更喜欢这个。

You might want to retain source order then you can just use this.

@import
  'foo',
  'bar';

I prefer this.

帅冕 2024-10-21 05:35:08

http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE .html#import

看起来不像。

如果这些文件中的任何一个始终需要其他文件,则让它们导入其他文件并且仅导入顶级文件。如果它们都是独立的,那么我认为你将不得不像现在一样继续这样做。

http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import

doesn't look like it.

If any of these files always require the others, then have them import the other files and only import the top-level ones. If they're all standalone, then I think you're going to have to keep doing it like you are now.

梦里南柯 2024-10-21 05:35:08

我也在寻找你问题的答案。对应于正确的 import all 函数不存在的答案。

这就是为什么我编写了一个 python 脚本,您需要将其放入 scss 文件夹的根目录中,如下所示:

- scss
  |- scss-crawler.py
  |- abstract
  |- base
  |- components
  |- layout
  |- themes
  |- vender

然后它将遍历树并查找所有 scss 文件。执行后,它将创建一个名为 main.scss 的 scss 文件,

#python3
import os

valid_file_endings = ["scss"]

with open("main.scss", "w") as scssFile:
    for dirpath, dirs, files in os.walk("."):
        # ignore the current path where the script is placed
        if not dirpath == ".":
            # change the dir seperator
            dirpath = dirpath.replace("\\", "/")

            currentDir = dirpath.split("/")[-1]
            # filter out the valid ending scss
            commentPrinted = False
            for file in files:
                # if there is a file with more dots just focus on the last part
                fileEnding = file.split(".")[-1]
                if fileEnding in valid_file_endings:
                    if not commentPrinted:
                        print("/* {0} */".format(currentDir), file = scssFile)
                        commentPrinted = True
                    print("@import '{0}/{1}';".format(dirpath, file.split(".")[0][1:]), file = scssFile)

这是输出文件的示例:

/* abstract */
@import './abstract/colors';
/* base */
@import './base/base';
/* components */
@import './components/audioPlayer';
@import './components/cardLayouter';
@import './components/content';
@import './components/logo';
@import './components/navbar';
@import './components/songCard';
@import './components/whoami';
/* layout */
@import './layout/body';
@import './layout/header';

I also search for an answer to your question. Correspond to the answers the correct import all function does not exist.

Thats why I have written a python script which you need to place into the root of your scss folder like so:

- scss
  |- scss-crawler.py
  |- abstract
  |- base
  |- components
  |- layout
  |- themes
  |- vender

It will then walk through the tree and find all scss files. Once executed, it will create a scss file called main.scss

#python3
import os

valid_file_endings = ["scss"]

with open("main.scss", "w") as scssFile:
    for dirpath, dirs, files in os.walk("."):
        # ignore the current path where the script is placed
        if not dirpath == ".":
            # change the dir seperator
            dirpath = dirpath.replace("\\", "/")

            currentDir = dirpath.split("/")[-1]
            # filter out the valid ending scss
            commentPrinted = False
            for file in files:
                # if there is a file with more dots just focus on the last part
                fileEnding = file.split(".")[-1]
                if fileEnding in valid_file_endings:
                    if not commentPrinted:
                        print("/* {0} */".format(currentDir), file = scssFile)
                        commentPrinted = True
                    print("@import '{0}/{1}';".format(dirpath, file.split(".")[0][1:]), file = scssFile)

an example of an output file:

/* abstract */
@import './abstract/colors';
/* base */
@import './base/base';
/* components */
@import './components/audioPlayer';
@import './components/cardLayouter';
@import './components/content';
@import './components/logo';
@import './components/navbar';
@import './components/songCard';
@import './components/whoami';
/* layout */
@import './layout/body';
@import './layout/header';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文