Last update on Monday, August 8th 2016

Using 3rd Party CSS With WebPack and Angular 2 ft Animate.css

Sometimes learning something can be complicated moreover when we need to handle many things at the same time. So if your boss tells you that you need to add some CSS from a third-party library into your Angular 2 components AND handle the WebPack configuration, you can feel overwhelmed like this guy:

dog meme

No need to panic, I'll get you through this in 5 min top chrono! We are going to use Animate.css because it's one of the best libraries ever created by a human being.

The installation

The easiest part:

npm i animate.css --save

Now that we got our library in our node_modules folder, we need to say 'Hey Component! The library is here, use it!'. Two cases here (before reading this, I advise you to go here first and get my cheatsheet for a reminder).

Isolating your CSS

First case here, you have your Angular 2 Component and you don't want other Components to use your external CSS.

It's very simple:

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

@Component({
  selector: 'home',  // <home></home>
  styles:[require('animate.css')],
  templateUrl: '<h1 class="animated infinite bounce">Example</h1> '
})

You only need to require('animate.css') and put it into your component's styles!

Let it leak!

angular 2 CSS Shadow DOM leak Let's say you have 50 Components ... You are not going to require Animate.css every time, just let it leak into your app!

It's better to import it into your parent/root Component so if you need to replace it, you don't have to search everywhere.

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

@Component({
  selector: 'root',  // <root></root>
  styles:[require('animate.css')],
  templateUrl: '<header></header><content></content> <footer></footer>',
  encapsulation: ViewEncapsulation.None
})

By setting encapsulation to ViewEncapsulation.None, Animate.css will be available for every components of your application!

Conclusion

Two things to remember here, requiring the module (require('moduleName')) and setting the encapsulation according to your needs, either to isolate it or to let it leak into your application while handling class names conflicts!

How To Handle Typings Using Webpack ft Lodash

How Parcel simplifies modern JavaScript projects

How to upload files to Amazon S3 with Angular 2 and Webpack

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven + other free stuff!