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

ben*_*lor 16 sass twitter-bootstrap angular-cli angular

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

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

.mybutton {
   @extend .btn;
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

  • SASS编译器抛出错误,因为它不知道 .btn
  • 如果我添加@import "bootstrap";到我的.scss-File,它将在每个组件css中呈现完整的Bootstrap-CSS

到目前为止我做了什么

  1. 添加@import "bootstrap";到我的app.component.scss
  2. 应用ViewEncapsulation.NoneAppComponent,所以角2不适影子DOM仿真和引导CSS适用于整个应用程序

     @Component({
        encapsulation: ViewEncapsulation.None
     })
    
    Run Code Online (Sandbox Code Playgroud)
  3. 包含以下块angular-cli-build.js,因此相对@import将起作用

    sassCompiler: {
      cacheExclude: [/\/_[^\/]+$/],
      includePaths: [ 'node_modules/bootstrap-sass/assets/stylesheets' ]
    },
    vendorNpmFiles: [
        ...
        'bootstrap-sass/assets/**/*'           
    ]
    
    Run Code Online (Sandbox Code Playgroud)

Ste*_*ele 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';
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这并不能解决原始海报不需要每个组件将样式注入页面的需要.如果他想对页面中每个X组件中的某些东西(比如按钮)使用@extend,那么该css将在页面上导入X次,每次都会覆盖另一个.这是一个糟糕的解决方案,但在angularCLI/Webpack提供更好的解决方案之前似乎无法改进 (5认同)