Steps to Include Custom CSS and JS Files in Ionic 3
When you work on an Ionic based project or any web project having JavaScript or CSS file, at times, you will forget to add your new JavaScript or CSS file onto the page. This often results in broken page. You will spend a lot of time troubleshooting the issue, before you realize that you just forgot to add the script or CSS tag. In this post, we will see the quick and easy steps to include custom CSS and JS files in Ionic 3. This saves your time and effort to fix the page.
Let us take a context for instance: While working with external libraries and NPM packages, you sometimes need to load JS/CSS files in a way, different from how the rest of your package is already loaded.
For example, if you are using ng2-CKEditor, you need to refer the ckeditor.js file in your index.html file:
Reference: https://www.npmjs.com/package/ng2-ckeditor
You can see that the above reference will be loaded from the cdn.ckeditor.com server. Following steps explain how easily we can load the external JS/CSS file from your application.
-
Install dependencies
npm install ng2-ckeditor
This will install the dependencies of ng2-ckeditor except for ckeditor.js in your node_modules folder.
Create custom copy config copy.config.js file is a custom dictionary that makes it easy to extend/override ionic build.
In Ionic, there is a default copy.config.js file in @ionic/app-scripts/config path. Check the following code:
module.exports = {
copyAssets: {
src: ['{{SRC}}/assets//*'],
dest: '{{WWW}}/assets'
},
copyIndexContent: {
src: ['{{SRC}}/index.html', '{{SRC}}/manifest.json', '{{SRC}}/service-worker.js'],
dest: '{{WWW}}'
},
copyFonts: {
src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/*/', '{{ROOT}}/node_modules/ionic-angular/fonts//*'],
dest: '{{WWW}}/assets/fonts'
},
copyPolyfills: {
src: [{{ROOT}}/node_modules/ionic-angular/polyfills/${process.env.IONIC_POLYFILL_FILE_NAME}
],
dest: '{{BUILD}}'
},
copySwToolbox: {
src: ['{{ROOT}}/node_modules/sw-toolbox/sw-toolbox.js'],
dest: '{{BUILD}}'
}
}
The default copy.config.js will look like the above code. Here copyAssets, copyIndexContent etc. denote the name of the entry. We can specify any name here.
-
src is the path of the file where you save the CSS/JS file.
-
dest is the destination where you need to send the file. Ideally, this will be your build folder.
This config will then take care of copying your CSS/JS 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:
"config": { "ionic_copy": "./config/copy.config.js" } Now you need to go ahead and create this file. Create a folder config at the root of your project and name the file inside as shown below: copy.config.js.
We can help!