Fix Chart.js adapter dynamic require error with CommonJS shim

Fixed "Dynamic require of 'chart.js' is not supported" error that occurred
when the Chart.js date adapter tried to use require() in the browser.

The issue was caused by marking chart.js as external in esbuild, which
prevented the bundler from resolving the require() call. The date adapter
uses UMD format and expects to find Chart.js via require() in CommonJS
environments.

Solution:
- Added a temporary window.require shim before loading the date adapter
- The shim returns window.Chart when require('chart.js') is called
- Cleaned up the shim after the adapter loads to avoid polluting globals
- This allows the adapter to find Chart.js and register itself properly

The weather charts now load without errors in both development and production.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Graham McIntire 2025-07-21 10:21:32 -05:00
parent c932abb434
commit 493805706f
No known key found for this signature in database

View file

@ -15,15 +15,31 @@ import '../vendor/oms.min.js';
// The UMD build automatically sets window.Chart
import '../vendor/chart.umd.js';
// 4. Load Chart.js date adapter AFTER Chart.js
// 4. Create a fake CommonJS environment for the date adapter
// The adapter expects to find Chart.js via require()
if (typeof window !== 'undefined' && !window.require) {
window.require = function(module) {
if (module === 'chart.js') {
return window.Chart;
}
throw new Error('Module not found: ' + module);
};
}
// 5. Load Chart.js date adapter AFTER Chart.js and require shim
// The adapter needs Chart to be available globally to register itself
import '../vendor/chartjs-adapter-date-fns.bundle.min.js';
// 6. Clean up the require shim
if (typeof window !== 'undefined' && window.require) {
delete window.require;
}
// Verify libraries are loaded
if (typeof window !== 'undefined') {
console.log('Vendor libraries loaded:', {
'Leaflet': !!window.L,
'Chart.js': !!window.Chart,
'Chart.adapters': !!(window.Chart && window.Chart.adapters)
'Chart.adapters': !!(window.Chart && window.Chart._adapters)
});
}