Node.js项目中require("jpgJs")返回空对象{}的问题求助
Root Cause
I’ve run into this exact issue before—here’s what’s going wrong: jpgjs’s export logic in jpg.js line 102 has a bug for Node.js environments. The condition if (typeof exports === "function") is incorrect because in Node.js, exports is always an object, not a function. That branch never triggers, so require("jpgjs") returns an empty {} instead of exposing the JpegDecoder that Utif relies on.
Solutions
Here are three solid ways to fix this, depending on your project needs:
1. Quick Manual Patch (For Testing/One-Off Projects)
- Head to
node_modules/jpgjs/jpg.jsin your project folder - Find line 102 and replace the faulty condition:
// Original code if (typeof exports === "function") // Replace with this to target Node.js exports if (typeof exports !== "undefined") - Save the file. Now
require("jpgjs")will correctly return theJpegDecoderUtif needs to work.
2. Create a Wrapper Module (Cleaner for Long-Term Use)
Avoid modifying node_modules directly by making a wrapper file (e.g., src/utils/jpgjs-fix.js):
// Load the raw jpgjs source (it attaches JpegDecoder to the global scope) require('jpgjs/jpg.js'); // Export the decoder for your project to use module.exports = global.JpegDecoder;
Then in your code, import from this wrapper instead of the raw jpgjs package:
const JpegDecoder = require('./utils/jpgjs-fix.js'); // Pass this to Utif or use it directly as needed
3. Use patch-package (Best for Team/Shared Projects)
This ensures the fix sticks even after running npm install:
- Install patch-package as a dev dependency:
npm install patch-package --save-dev - Modify
node_modules/jpgjs/jpg.jsline 102 as described in solution 1 - Generate a persistent patch file:
npx patch-package jpgjs - Commit the generated
patches/jpgjs+<version>.patchfile to your repo. Now every time your team runsnpm install, the patch will automatically apply.
内容的提问来源于stack exchange,提问作者Kenzie Revoyr

