Include CSS+JS Files from NPM Packages with Ionic [v3]

ionic-include-external-files-header

When working with external libraries and NPM packages, you sometimes need to load those files in a different way than the rest of your packages is already loaded.

In this Quick Win you will see how to easily install and integrate those plugins so you can use them just like any other library in your general Ionic workflow. Afterwards you can load CSS or JS files directly during the build process of your app.

1. Install dependencies

Of course you start by installing a NPM package to your Ionic app. In this case, I used the css-animator package to easily add animations to my app:

For most packages you only need to follow their instructions for installation and installing the dependency is enough. However, this lib was relying on another library and their CSS file, so I had to copy that file (I didn’t want to use the CDN file).

2. Create custom copy config

For this case we can create a custom copy config which will be executed during the build process. Ionic makes this really easy, so you can always be sure that you have the power to make tweaks to the build process!

This config will then take care of copying the CSS file into the build folder, just like your service-worker or assets are copied.

We start by adding an entry to our package.json which passes a custom config to the ionic_copy hook:

Now we need to go ahead and create this file, therefore create a folder config at the root of your project and inside a file named copy.config.js.

This file is based on the original Ionic source file which will be used if you don’t specify anything here!

You can copy that file and add an entry to copy your CSS or JS or use my code below. I only added the copyAnimateCss section which copies the CSS file out of the node_modules folder right into the build folder:

To find the correct path, just check your node_modules folder and find the installed plugin. In my case this was the packages folder:
ionic-external-packages

From that folder you can gather the right path, now there’s only one step missing.

3. Load in your App

We have installed the package and copied it during build, now we need to acutally link to it and use it!

To do this last step, open your src/index.html and somewehre inside the head (for CSS) add an entry like this:

Remember, the file was copied directly to the build folder, and that’s the place our app will find it during runtime.

No we don’t need to use any external hosted CDN files and our “problematic” package is perfectly integrated into our Ionic workflow!

Tweet
Reddit
+1
Share23
Email
23 Shares