首页 文章

访问角度2组件中的bootstrap scss变量

提问于
浏览
11

我正在开发一个使用Angular CLI构建的新Angular2项目,并将项目配置为使用SCSS . 我已将Bootstrap 4成功加载到我的 styles.scss 文件中,但是如果我尝试访问任何Bootstrap(或我自己在组件中 styles.scss 中定义的变量),我会得到 Undefined Variable 构建错误 .

stylesstyles 节点的主条目之前编译的组件样式文件是什么?我怎样才能使在该全局级别定义的任何变量可用于应用程序中的所有组件?谢谢!

angular-cli.json

"apps": [
  {
    ...
    "styles": [
      "styles/styles.scss"
    ],
    ...
  }
]

styles.scss

// Bootstrap
$enable-flex: true; // Enable Flexbox mode
@import "../../node_modules/bootstrap/scss/bootstrap";

component

.navbar {
  background: $brand-primary; // Undefined variable here
}

3 回答

  • 3

    仅仅因为您将引导程序4导入 styles.scss 并不意味着组件上的 .scss 文件可以访问它 .

    component.scss 上,您必须导入Bootstrap变量:

    @import '~bootstrap/scss/_variables.scss';
    
    .navbar {
      background: $brand-primary; // No more Undefined variable here
    }
    

    解释

    很多人似乎对此感到困惑,你不应该将 bootstrap.scss 导入你的组件,你应该只导入你需要的东西 .

    如果仔细观察the source code of bootstrap.scss,它们会将所有内容分隔在不同的文件中 . 您有 mixins 文件夹和 _variables.scss 文件 . 这些应该是您在组件上导入的唯一内容,以避免CSS重复 .

    这会增加我的包大小,在每个组件上导入这些东西吗?

    不,它不会 . 为什么? mixinsvariables 是特定的(至少目前为止)所以当您将所有变量导入到组件中时,如下所示:

    @import '~bootstrap/scss/_variables.scss';
    
    .navbar {
      background: $brand-primary;
    }
    

    它的输出CSS将是:

    .navbar {
      background: #007bff;
    }
    

    编译到CSS后,其余变量将被丢弃 .

  • 2

    有几个人在每个组件中都建议 @import variables.scss 但我觉得这有点乱 . 这样做对我们公司的CSS架构方式也不起作用 . 我最终朝这个方向前进,使我能够使用变量,mixins,以及扩展样式 . 这也允许我在一个位置管理所有CSS .

    我目前正在开发一个由Angular2 CLI生成的项目 . 所以有一个主要的style.scss


    我能够实现此目的的另一种方法是执行以下操作:

    • app.component.ts 文件中删除 styleUrls .
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html'
        // styleUrls: ['./app.component.scss']
    });
    
    • 我管理主 styles.scss 中所有较少的文件 . 所以我目前的设置看起来像:
    // Bootstrap
    @import "../node_modules/bootstrap-less/bootstrap/index";
    
    // Company Branding
    @import "theme/index";
    
    // Components
    @import "app/app.component.scss";
    @import "app/search/search.component.scss";
    

    希望这种替代解决方案对某人有所帮助 .

  • 20

    创建一个_colors.scss文件,复制内部的所有颜色变量并将该文件导入component.scss文件中 .

相关问题