首页 文章

Angular2:如何在Angular-CLI中使用带有@extend和mixins的bootstrap-sass?

提问于
浏览
16

我正在尝试使用带有Angular 2的Twitter Bootstrap,SCSS和angular-cli生成的脚手架

我想应用最佳实践,不要使用Bootstrap特定的CSS类来丢弃我的标记 . 相反,我想通过@extend或mixins来应用/使用它们:

.mybutton {
   @extend .btn;
}

我的问题:

  • SASS编译器抛出错误,因为它不知道 .btn

  • 如果我将 @import "bootstrap"; 添加到我的 .scss -File,它将在每个组件css中呈现完整的Bootstrap-CSS

到目前为止我做了什么

  • @import "bootstrap"; 添加到我的 app.component.scss

  • ViewEncapsulation.None 应用于 AppComponent ,因此Angular 2不应用Shadow DOM仿真,Bootstrap CSS适用于整个应用程序

@Component({
    encapsulation: ViewEncapsulation.None
 })
  • 将以下块包含在 angular-cli-build.js 中,因此相对 @import 将起作用
sassCompiler: {
  cacheExclude: [/\/_[^\/]+$/],
  includePaths: [ 'node_modules/bootstrap-sass/assets/stylesheets' ]
},
vendorNpmFiles: [
    ...
    'bootstrap-sass/assets/**/*'           
]

1 回答

  • 8

    最新版本的angular-cli适用于webpack,它没有 angular-cli-build.js ,所以你可以忽略它,如果你升级 .

    我也不会禁用视图封装 . 如果需要全局样式,请将它们添加到全局样式表中 . (angular-cli在你的src文件夹中创建一个,通常是一个css文件,所以使用 -style=scss 标志创建你的应用程序或在你的 angular-cli.json 中更改它) .

    所以,如果你有最新的cli版本,你可以导入bootstrap-sass mixins . 例如,你的 app.component.scss

    // core
    @import '~bootstrap-sass/assets/stylesheets/bootstrap/variables';
    @import '~bootstrap-sass/assets/stylesheets/bootstrap/mixins';
    // buttons
    @import '~bootstrap-sass/assets/stylesheets/bootstrap/buttons';
    

    为了能够编译你的bootstrap,sass需要'核心'导入 . 你可能应该将它们移到自己的mixin中 .

    如果您还想使用glyphicons,还必须相对于其使用的scss文件设置 $icon-font-path bootstrap变量 . (例如 $icon-font-path: '../node_modules/bootstrap-sass/assets/fonts/bootstrap/';

相关问题