Vingtoft
Vingtoft

Reputation: 14606

Angular2: How to import a stylesheet from node_modules?

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']
})

Upvotes: 7

Views: 16905

Answers (3)

daisura99
daisura99

Reputation: 1110

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.

Upvotes: 3

sickelap
sickelap

Reputation: 897

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.

Upvotes: 17

jackstrapp
jackstrapp

Reputation: 313

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.

Upvotes: 1

Related Questions