opencv-js icon indicating copy to clipboard operation
opencv-js copied to clipboard

Fix Next.js 14.1.0 compatibility by improving UMD pattern in opencv.js

Open Copilot opened this issue 5 months ago • 0 comments

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:

  1. module.exports could be null or undefined in certain contexts
  2. The this context passed to the UMD wrapper was undefined
  3. The original UMD pattern's condition typeof module === 'object' && module.exports would fail when module.exports was falsy
  4. This caused the code to fall through to the else clause and attempt root.cv = factory() where root was undefined

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.

Copilot avatar Sep 05 '25 03:09 Copilot