opencv-js
opencv-js copied to clipboard
Fix Next.js 14.1.0 compatibility by improving UMD pattern in opencv.js
This PR fixes the compatibility issue with Next.js 14.1.0 where opencv.js would throw a TypeError: Cannot set properties of undefined (setting 'cv') error during module loading.
Problem
The error occurred when Next.js 14.1.0 created an environment where:
-
module.exportscould benullorundefinedin certain contexts - The
thiscontext passed to the UMD wrapper wasundefined - The original UMD pattern's condition
typeof module === 'object' && module.exportswould fail whenmodule.exportswas falsy - This caused the code to fall through to the else clause and attempt
root.cv = factory()whererootwasundefined
Solution
Improved CommonJS Detection:
// Before: typeof module === 'object' && module.exports
// After: typeof module === 'object' && module !== null
Added Safe Root Fallback:
// Ensure root exists before setting properties
root = root || (typeof globalThis !== 'undefined' ? globalThis :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self : {});
Better UMD Invocation:
// Use safer global object detection when calling the UMD function
}(typeof globalThis !== 'undefined' ? globalThis :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self :
typeof window !== 'undefined' ? window : this, function () {
Testing
- ✅ All existing tests continue to pass
- ✅ Added comprehensive test suite for Next.js compatibility scenarios
- ✅ Verified the fix handles various edge cases (null exports, undefined context, etc.)
- ✅ Maintains full backward compatibility with all supported environments
Usage
Users can now successfully use opencv.js in Next.js 14.1.0 projects without needing to downgrade:
import cv from '@techstark/opencv-js';
cv.onRuntimeInitialized = () => {
console.log('OpenCV.js is ready!');
// OpenCV functions work normally
};
Fixes #54.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.