简体   繁体   中英

Angular 2 Webpack 2 - Sass not working in component

I have been following the guide here https://github.com/AngularClass/angular2-webpack-starter/wiki/How-to-include-SCSS-in-components in terms of incorporating scss files as my styles for angular 2 components, but it's not working.

How do I incorporate scss files into my angular 2 components with webpack?

Here is the main component:

import { Component } from '@angular/core';


@Component({
    selector: 'my-app',
    templateUrl: 'src/app/app.component.html',
    styleUrls: [ 'src/app/app.component.scss' ]
})
export class AppComponent {
    constructor() {}

    name: string = 'My Demo';
}

I know the article recommends using raw-loader in my webpack config but that's not working either

The scss just remains in the without being preprocessed.

You can see the particulars for my basic project at the plnkr here: https://plnkr.co/edit/eG1POBcBL8kGpvrhh3yW?p=info

Follow the README instructions to build and serve.

Doesn't seem like there's much up to date documentation on including scss files in components?

If you want a new project with SCSS working out of the box, generate it with angular-cli and you're good to go. Much easier then implementing sass by yourself imo.

ng new sassy-project --style=sass

or:

ng new sassy-project --style=scss

You can do thin in next way:

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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM