Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Sep 5, 2025

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.

Co-authored-by: ttt43ttt <132509+ttt43ttt@users.noreply.github.com>
@Copilot Copilot AI changed the title [WIP] doesn't support nextjs 14.1.0 Fix Next.js 14.1.0 compatibility by improving UMD pattern in opencv.js Sep 5, 2025
@Copilot Copilot AI requested a review from ttt43ttt September 5, 2025 03:48
Copilot finished work on behalf of ttt43ttt September 5, 2025 03:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

doesn't support nextjs 14.1.0

2 participants