【问题标题】:Compile css and sass files to single css file using gruntjs使用 gruntjs 将 css 和 sass 文件编译为单个 css 文件
【发布时间】:2014-12-26 06:49:22
【问题描述】:

我有一个 bootstrap.css 文件,我想用我的自定义样式从 style.sass 编译成单个输出文件,例如 - style.css。 对于 sass 编译,我使用带有 grunt-contrib-sass 扩展的 gruntjs。我的 sass 的 Gruntfile.js 配置如下所示:

sass: {
    dist: {
        options: {
            //style: 'compressed',
            style: 'expanded',
            lineNumbers: true
        },
        files: {
            'build/styles/style.css': 'src/styles/style.sass'
        }
    }
}

我尝试将 bootstrap.css 导入 sass 文件,但它只在输出 css 中生成下一个代码(这是正确的行为 http://sass-lang.com/documentation/file.SASS_REFERENCE.html#import):

@import url(bootstrap.css);

.....
/*my style.sass rules*/

我什至尝试按照连接和处理的顺序列出多个文件,就像在 uglifier 设置中一样:

files: {
    'build/styles/style.css': ['src/styles/bootstrap.css', 'src/styles/style.sass']
}

但这只会将 bootstrap.css 添加到最终 style.css 文件中,而忽略 style.sass 的存在。

由于我是 gruntjs 的新手,所以我不知道应该如何正确完成。

【问题讨论】:

  • 您是否尝试过删除 url() 以便获得@import "bootstrap.css;"?我只导入这样的“.scss”文件:@import "bootstrap";
  • @import url(...);是来自输出文件的 css。问题是,SASS 通过规则扩展了 css 默认导入功能,您可以在上面的参考资料中找到。
  • 我明白了,如果您使用了 scss 格式,您可以将引导程序的格式更改为 bootstrap.scss 并使用 @import "bootstrap"; 导入,因为 vanilla CSS 是有效的 SCSS。基本上你有三个选择; 1. 使用 sass 语法重写 bootstrap,2. 将 sass-file 更改为 scss 语法,或者 3. 单独渲染 sass 并通过另一个 grunt 扩展与 bootstrap 合并。
  • 我明白了,谢谢。我会找到一些类似“concat”或类似的扩展名。

标签: css sass gruntjs grunt-contrib-sass


【解决方案1】:

Grunt 配置正确。您的文件没有被导入的原因是因为 SASS 的设计工作方式。

SASS documentation 声明:

默认情况下,它会查找要直接导入的 Sass 文件,但在某些情况下它会编译为 CSS @import 规则:

  • 如果文件的扩展名是 .css。
  • 如果文件名以 http:// 开头。
  • 如果文件名是 url()。
  • 如果@import 有任何媒体查询。

由于您要导入的文件具有 .css 扩展名,因此不会直接导入,但仍是标准 CSS @import

您可以通过三个选项来解决此问题:

  1. 将包含的文件重命名为_bootstrap.scss。 (如果您不添加下划线,bootstrap.css 将与您的主输出文件一起创建,这是不必要的。)
  2. Bootstrap SCSS source 包含为项目的依赖项并针对它进行构建。通过在项目根文件夹中键入 $ bower install bootstrap-sass-official 来安装 Bootstrap source using Bower。 (有关设置 Bower 的说明,请参阅 Bower website。)然后您可以将上面的导入替换为 @import 'bower_components/bootstrap-sass-official/assets/stylesheets/bootstrap';
  3. 在构建过程中,使用grunt-contrib-concat 等串联库将Bootstrap.css 和主样式表结合起来。

如果您手动将引导 CSS 文件下载到项目中,则第一个选项很好,但是,如果您将其作为依赖项包含在 npm/bower 中,则不理想。

我会推荐第二个选项,因为从源代码构建 Bootstrap 不仅可以解决您的问题,而且允许自定义 Bootstrap 变量以适应您的主题,而不是用后续的样式规则覆盖它们。唯一的缺点是,由于 Bootstrap 源的 SASS 构建相当大,您的构建过程可能会稍长一些。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2020-07-08
    • 2020-04-06
    • 1970-01-01
    • 2013-11-10
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多