Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: How to import a stylesheet from node_modules?

Tags:

css

angular

Question: In my Angular2 (4.0) app, how can I import stylesheets (css) from a module in node_modules?

I have a module located here:

node_modules/@swimlane/ngx-datatable

I want to import this stylesheet:

node_modules/@swimlane/ngx-datatable/release/index.css

I've tried the following approaches, with no luck:

In my components own scss file:

@import '~@swimlane/ngx-datatable/release/index.css';

In my component:

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'site_table',
  template: require('./site_table.html'),
  styleUrls: ['./site_table.scss', '@swimlane/ngx-datatable/release/index.css']
})
like image 272
Vingtoft Avatar asked May 02 '17 12:05

Vingtoft


Video Answer


3 Answers

Because you're already using SCSS, in your ./site_table.scss import it like so

@import "~swimlane/ngx-datatable/release/index";

Note: do not add the extension.

It will import stylesheet from node package. That served my well, hope it will do for you too. That way you just have to use single stylesheet in your component and it will look cleaner.

like image 107
sickelap Avatar answered Oct 23 '22 22:10

sickelap


If you are using new the angular-cli with the angular.json file and not webpack, the tilde (~) in @sickelap's answer probably doesn't work for you.

Instead what you can do is add this in your angular.json file:-

        ...
        "styles": [
          ...
        ],
        "stylePreprocessorOptions": {
          "includePaths": [
            "node_modules/@swimlane"
          ]
        },
        ...

Then, in your component's .scss file, insert this:

@import "ngx-datatable/release/index";

Note that the .css extension is not required.

like image 2
daisura99 Avatar answered Oct 23 '22 22:10

daisura99


Try it with a complete relative url:

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'site_table',
  template: require('./site_table.html'),
  styleUrls: [
          './site_table.scss', 
          '../../node_modules/@swimlane/ngx-datatable/release/index.css' 
  ]
})

Didn't tried your notation but node package resolution might not work without webpack. I may be wrong though.

like image 1
jackstrapp Avatar answered Oct 23 '22 20:10

jackstrapp