How to use SASS/SCSS in angular application

后端 未结 4 1817
梦毁少年i
梦毁少年i 2021-01-16 09:51

I am trying to build a color theme functionality in angular2 application using sass. My header.component.scss file is:

$head-color: #f11;
h1{
    color: $hea         


        
相关标签:
4条回答
  • 2021-01-16 10:26

    Instead of using styleUrls use styles and convert the file to a string.

    styles: [require('./header.component.scss').toString()]
    

    For your webpack config I think you have to many loaders. I believe you should be able to just have

    'raw-loader!sass-loader' 
    

    My current config is:

    {
      test: /\.scss$/,
      exclude: /node_modules/,
      loader: 'raw-loader!postcss-loader!sass-loader'
    },
    
    0 讨论(0)
  • 2021-01-16 10:29

    Command line inside project folder where your existing package.json is: npm install node-sass sass-loader raw-loader --save-dev

    In webpack.common.js, search for "loaders:" and add this object to the end of the loaders array (don't forget to add a comma to the end of the previous object):

    {
      test: /\.scss$/,
      exclude: /node_modules/,
      loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
    }
    

    Then in your component:

    @Component({
      styleUrls: ['./filename.scss'],
    })
    

    If you want global CSS support then on the top level component (likely app.component.ts) remove encapsulation and include the SCSS:

    import {ViewEncapsulation} from '@angular/core';
    
    @Component({
      selector: 'app',
      styleUrls: ['./bootstrap.scss'],
      encapsulation: ViewEncapsulation.None,
      template: ``
    })
    class App {}
    
    0 讨论(0)
  • 2021-01-16 10:31

    You're using StyleUrls instead of Styles

    Change styleUrls: ['app/header/header.component.scss'] by styles: [ String(require('./header.component.scss')) ]

    See more https://stackoverflow.com/a/38349028/689429

    Update your errors if necessary

    0 讨论(0)
  • 2021-01-16 10:33

    In my own project this is what I used.

    form-automobile.component.ts

    @Component({
        selector: 'form-automobile',
        templateUrl: './form-automobile.component.html',
        styleUrls: ['./form-automobile.component.scss'],
    })
    

    form-automobile.component.scss

    $myuglycolor: lime;
    
    label {
        width: 100%;
        background-color: $myuglycolor
    }
    

    webpack.config.common.js

    {
        // Load component styles here. When loaded with styleUrls in component, array of string of styles is expected.
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: ['css-to-string-loader','css-loader','sass-loader']
    }
    
    0 讨论(0)
提交回复
热议问题