How do I include javascript+css from node_modules in ionic 2?

前端 未结 1 1376
醉梦人生
醉梦人生 2021-02-06 02:15

I need to include fullcalendar and chart.js within my ionic 2 app. (ionic 2 RC.3) I have used npm to install the relevant modules, and the scripts are within my node_modules fo

1条回答
  •  别跟我提以往
    2021-02-06 02:38

    I believe this is the cleanest way I've seen it done.

    We're essentially going to override the copy portion of the ionic build script. They've created the build script to encourage this and make it simple.

    Assuming you've already used npm to install whatever library you need:

    npm install chart.js --save
    

    (which installs the chart.js library into the node_packages folder in the root of the project)

    Look at /node_modules/@ionic/app-scripts/config/copy.config.js. This is what we are overriding, so copy it's contents to a file at /config/copy.config.js (You'll need to create the /config folder).

    module.exports = {
      include: [
        {
          src: '{{SRC}}/assets/',
          dest: '{{WWW}}/assets/'
        },
        {
          src: '{{SRC}}/index.html',
          dest: '{{WWW}}/index.html'
        },
        {
          src: '{{SRC}}/manifest.json',
          dest: '{{WWW}}/manifest.json'
        },
        {
          src: '{{SRC}}/service-worker.js',
          dest: '{{WWW}}/service-worker.js'
        },
        {
          src: 'node_modules/ionic-angular/polyfills/polyfills.js',
          dest: '{{BUILD}}/polyfills.js'
        },
        {
          src: 'node_modules/ionicons/dist/fonts/',
          dest: '{{WWW}}/assets/fonts/'
        },
        {
          src: './node_modules/chart.js/dist/Chart.bundle.min.js',
          dest: '{{BUILD}}/Chart.bundle.min.js'
        },
      ]
    };
    

    The last section was the one we added on, to copy the chart.js file to somewhere that will actually get pulled into the build.

    To get our script be used, package.json needs to be told about it, so add this "config" section to your /package.json file:

    "config": {
        "ionic_copy": "./config/copy.config.js"
    },
    

    Now when you build, the file will be copied, and it's obviously easier after the first one is done, to add more. There are other portions of the ionic build process you can override as well, it's worth looking in to.

    https://ionicframework.com/docs/v2/resources/app-scripts/

    Now you can call it in easily, one option is inside of index.html:

    
    

    The benefits are, if you install a module update, changed files will get updated in your build, and also, everything works out easily with vcs and setting up new environments, as the dependencies are handled by npm, and our script extension takes care of everything else. :-)

    Hope that helps! :-)

    0 讨论(0)
提交回复
热议问题