Search code examples
javascriptrequirejsqlikviewqliksense

Qlik How to import JS Libraries that are Depended of ether other


I am building a custom extension and require Chartjs to do so.

I have the following imports

define( [
        'jquery',
        './PropertiesPannel',
        '//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js',
        '//cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js',
        '//cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.5/dist/chartjs-plugin-zoom.min.js'
    ],
    function ( $, ProperitesPannel, Chart) {
        'use strict';
....

I am getting the following Console error.

hammerjs.js:1 Uncaught SyntaxError: Unexpected token '<'
3setup-view.d91ae8b7669a979d2ec1.js:8 TypeError: Cannot read property 'helpers' of undefined
    at chartjs-plugin-zoom.min.js:11
    at Object.execCb (setup-view.d91ae8b7669a979d2ec1.js:8)
    at n.check (setup-view.d91ae8b7669a979d2ec1.js:8)
    at n.<anonymous> (setup-view.d91ae8b7669a979d2ec1.js:8)
    at setup-view.d91ae8b7669a979d2ec1.js:8
    at setup-view.d91ae8b7669a979d2ec1.js:8
    at each (setup-view.d91ae8b7669a979d2ec1.js:8)
    at n.emit (setup-view.d91ae8b7669a979d2ec1.js:8)
    at n.check (setup-view.d91ae8b7669a979d2ec1.js:8)
    at n.enable (setup-view.d91ae8b7669a979d2ec1.js:8)

I understand the the chartjs Plugin file requires the chart file and hammer. how can i get these linked up?


Solution

  • This one is quiet problematic... The chartjs plugin tries to load chart.js which is not a valid module id but a file name. So RequireJS tries to load it as file even when I setup it up in the require.config.paths... So got a little workaround here:

    <script src=https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js></script>
    <script>
        require.config({
            paths: {
                jquery: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min',
                'chart': '//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle',
                hammerjs: '//cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min'
            }
        });
    
        var originalDefine = define;
    
        window.define = function (a, b, c) {
            // when chartjs-plugin-zoom.min.js tries to load chart.js, load the chart module from the defined paths :)
            if (a && a.length && a[0] === 'chart.js') {
                a[0] = 'chart';
            }
            originalDefine(a, b, c);
        };
    
        require([
            'jquery',
            'chart',
            'hammerjs',
            '//cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.5/dist/chartjs-plugin-zoom.min.js'
        ], function ($, chart, hammer, chartjs) {
            'use strict';
            console.log('hello world');
            console.log($, chart, hammer, chartjs);
        });
    </script>
    

    It loads fine so you are good to go