dat.gui库无法运行:Uncaught TypeError报错问题求助
Uncaught TypeError: this.onResize is not a function in dat.gui Hey there, that error you're hitting when initializing dat.gui is super common, and it almost always boils down to a version mismatch or incorrect import setup. Let's break down how to fix this step by step:
1. Double-check how you're importing dat.gui
You mentioned you just finished importing the library—first make sure you're using the right build for your setup:
- If you're using a CDN: Skip the ES module builds (like
dat.gui.esm.js) and go for the standard UMD version (dat.gui.min.js). ES modules require specific import syntax, which might not be what you're using right now. - If you installed via npm: Make sure you're importing the
GUIclass correctly instead of grabbing the whole module:import { GUI } from 'dat.gui'; const gui = new GUI();
2. Verify dat.gui version compatibility
That this.onResize error pops up a lot when folks use a newer dat.gui version (v0.7.9+) with the old global dat.GUI() syntax, or vice versa (old library file with new import patterns).
Quick fix: Roll back to a stable older version
Try using v0.7.7 of dat.gui—it's a reliable release that doesn't have this initialization quirk. You can grab it via CDN easily.
3. Validate your initialization logic
Looking at your code, you're using:
var gui = dat.GUI();
This is correct for older, globally-scoped versions of dat.gui. To make sure the global dat object is actually available, add a quick check at the start of your loadScene function:
function loadScene() { console.log("Is dat available?", typeof dat); // Should log "object" if it's loaded right console.log("LOG: Program start"); // Rest of your code... }
If this logs undefined, your library isn't loading at all—double-check your script tag path or npm import.
4. Rule out conflicts
- Make sure no other scripts on your page are overwriting the
datglobal variable or theGUIclass. - Clear your browser cache—sometimes old, broken versions of the library get stuck in cache.
A quick note on your code
While it's not causing the current error, your createSphere function has a typo in the log message ("LOG: Box created" instead of "LOG: Sphere created"). Just a heads-up for later debugging!
To test things quickly, comment out all your Three.js code temporarily and just initialize dat.gui. If that works, you know the issue was with the library setup, not a conflict with your scene code.
内容的提问来源于stack exchange,提问作者Teije

