I am trying to set RequireJS require.config() for Javascript libraries on the fly. I am using this configuration for Moment.js, Chart.js and Chartjs Streaming Plugin:
require.config({
paths: {
'moment': '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min',
'chart': '//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart',
'streaming': '//cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-streaming.min'
},
shim: {
'chart': {
exports: 'C'
},
'streaming': {
exports: 'C',
deps: ['moment','chart']
}
}
});
I am trying to create a simple line chart using this Javascript code:
require(['moment', 'chart', 'streaming'], function (moment, C, streaming) {
var ctx = document.getElementById('myChart').getContext('2d');
var chrt = new C.Chart(ctx, {
type: 'line',
data: { datasets: [{ data: [1,2,3,4,5] },{ data: [-1,0,1,2,3] }] }
})
})
This script creates a simple Chart.js chart if I do not include the chartjs-plugin-streaming.min.js code.
However, when I try to add that script using the require.config() above, I see in Chrome that I am getting a 500 Error for "chart.js" even thought Chart.js is already loaded:
My question is, am I requiring the chartjs-plugin-streaming and its dependencies correctly, please? Or is there another problem?
chartjs-plugin-streaming
is looking for 'chart.js'
as you can see in index.js in the GitHub source and below.
'use strict';
import Chart from 'chart.js';
import moment from 'moment';
import realTimeScale from './scales/scale.realtime';
import streamingPlugin from './plugins/plugin.streaming';
realTimeScale(Chart, moment);
var plugin = streamingPlugin(Chart);
Chart.plugins.register(plugin);
export default plugin;
Because it has the '.js'
extension in the name for the import
, you have to export something in your require.config
with that name.
You need a RequireJS map
so chartjs-plugin-streaming
can find that file. Here's the fixed require.config
.
require.config({
paths: {
moment: "//cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min",
chart: "//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min",
streaming: "//cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-plugin-streaming.min"
},
shim: {
chartjs: {
exports: "C"
},
streaming: {
exports: "C",
deps: ["moment", "chart"]
}
},
map: {
streaming: {
"chart.js": "chart"
}
}
});
require(["moment", "chart", "streaming"], function(moment, chart) {
var ctx = document.getElementById("myChart").getContext('2d');
var chrt = new chart.Chart(ctx, {
type: "line",
data: { datasets: [{ data: [1, 2, 3, 4, 5] }, { data: [-1, 0, 1, 2, 3] }] }
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>