Use 3rd party CSS with Ionic

Viewed 798

I am currently porting one of my Cordova+Angular2 projects to Ionic 3.8+Angular 4.1.3. My project uses a few 3rd part JS and CSS libraries like Font awesome, Slick carousel etc. In the previous version, I used webpack for packaging my app and below is how I managed 3rd party css and JS.

.angular-cli.json

"styles": [
    "styles.css",
    "css/animate.css",
    "css/font-awesome.css",
    "css/slick.css",
    "css/slick-theme.css"
  ],
  "scripts": [
    "scripts/jquery-3.2.1.min.js",
    "scripts/slick.min.js",
    "scripts/slideout.min.js"
  ],

How do I achieve the same with Ionic? I have gone through the solutions available online, but most of them recommend combining the css to the global scss file, or even tweaking ionic. Is there a straightforward solution for this as with angular cli?

1 Answers

In Ionic 3 this is actually pretty tricky, we'll have to dig a bit into Ionic App Scripts. The easier way is to add a link to your index.html as Duannx points out in the comments.

The good news is: In Ionic v4 there will be no Ionic App Scripts anymore and you'll be able to manage your custom CSS as pointed out above using an angular.json file. See the official v4 announcement here.


If we want to do it the right way in Ionic v3 we'll have to do the following after installing our custom CSS solution via npm e.g.:

npm install slick-carousel

1. Copy and edit the sass.config.js from Ionic App Scripts

Go to node_modules/@ionic/app-scripts/config and copy the sass.config.js file. I copied it to my project's root directory. Then edit the file: Add paths to your custom CSS to the includePaths section, e.g. I added the path to the slick-carousel node_module:

includePaths: [
    'node_modules/ionic-angular/themes',
    'node_modules/ionicons/dist/scss',
    'node_modules/ionic-angular/fonts',
    'node_modules/slick-carousel/slick'
  ],

2. Link our new sass.config.js in package.json

Now let's link our new SASS configuration in our package.json. This is well documented in the App Scripts readme. Add a config section with following content:

"config": {
    "ionic_sass": "./sass.config.js"
  }

As pointed out before my new sass.config.js is in my projects root directory. If you copied it elsewhere make sure to adjust the path accordingly.

3. Import custom css files using @import

Now we can finally import our custom CSS using @import. A good place to do this is variables.scss.

Sad thing is: For slick-carousel we're not done yet. We'll also have to copy some fonts. But this shouldn't be to hard, we can do the same as above with copy.config.js and editing the copyFonts section.

Related