Loading Highcharts with require.js

2019-01-23 13:34发布

问题:

I have been trying for some time with little success to be able to load highcharts as a require module. I was wondering if anyone had managed to get this working, or if they had any pointers to get me on the right track?

Thank you

回答1:

With require.js 2.1.0+ a plugin is not necessary. You can include Highcharts with a shim:

require.config({
  paths: {
    require: "libs/require",
    jquery: "libs/jquery",
    highcharts: "libs/highcharts"
  },
  shim: {
    highcharts: {
      exports: "Highcharts",
      deps: ["jquery"]
    }
  } // end Shim Configuration
});


回答2:

I just got it to work as follows:

  1. Add this at the top:

    define(['jquery'], function (jQuery) {
    
  2. Add this at the very end:

    return window.Highcharts; });

This assumes you have jquery already defined, eg

require.config({
    paths: {
        'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min'
     }
});

You can follow this general approach for most third party libraries. For example, I did this for jquery.tmpl.js and knockout.js.



回答3:

Using the recent use.js plugin is definitely the way to go. Editing third party libs as suggested in my previous answer is a pain for maintainability.



回答4:

A minimal example of a recent approach for Highcharts with a module (JSFiddle example):

require.config({
    paths: {
        highcharts: "https://code.highcharts.com/highcharts",
        highcharts_exporting: "https://code.highcharts.com/modules/exporting"
    }
});

require(['highcharts', 'highcharts_exporting'], function(Highcharts, exporting) {
    exporting(Highcharts); // We need to initialize module files and pass in Highcharts

    Highcharts.chart('container', {
        series: [{
            data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        }, {
            data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        }]
    });
});

See this Highcharts documentation for a usage description.