How to include custom js script in ionic 2


#1

I have a bunch of javascript files that I would like to include in my Ionic 2 application. I know if it’s added to the index.html file it doesn’t get bundled into the build folder. How do I solve this problem? I digged around and found scripts-copy but wasn’t sure how to go about it because I couldn’t find any beginner friendly step by step guide.


#2

You need follow this steps:

  • Install / copy the JS files in to the project, you can use npm or copy to a specific folder.
  • Add to your package.json the a config section, here is a sample:
...
"config": {
  "ionic_copy": "./config/copy.config.js"
},
...
  • create a copy file in the path ./config/copy.config.js, here is a sample:
module.exports = {
  copyAssets: {
    src: [
      '{{SRC}}/assets/**/*',
      '{{ROOT}}/node_modules/jquery/**/*'
    ],
    dest: '{{WWW}}/assets'
  },
  // Here is my custom script
  copyChart: {
    src: [
      '{{ROOT}}/node_modules/chart.js/dist/**/*'
    ],
    // Very important, the dest folder to reference from index.html
    dest: '{{WWW}}/assets/libs/chart.js'
  },
  // End Custom Script
  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/polyfills.js'],
    dest: '{{BUILD}}'
  },
  copySwToolbox: {
    src: ['{{ROOT}}/node_modules/sw-toolbox/sw-toolbox.js'],
    dest: '{{BUILD}}'
  }
}
  • Modify the file src/index.html to add the reference to the scripts
<script src="assets/libs/chart.js/Chart.js"></script>

I think this is the basic steps, i hope that works for you

Regards


#3

If you’re looking for something “beginner-friendly”, I would strongly urge that you give up on this, and instead search for some existing Angular-compatible modules that incorporate the functionality you desire. It is going to save you a lot of wasted time, and the end result will be a much more idiomatic and easy-to-maintain code base.