-
-
Notifications
You must be signed in to change notification settings - Fork 0
Advanced Topics
Q: After upgrading Three.js beyond R148, my previously working JavaScript code is now throwing errors.
A: Three.js underwent significant changes with R148 (released in December 2022),
primarily driving the full adoption of ES Modules (ESM). This shift deprecates the global scope,
meaning code loaded with <script type="module"> will, by default, have its access to external scopes concealed.
Below are common errors resulting from this change and their solutions.
1. Changes in import Path Resolution
ESM uses import statements for module loading. With Three.js R148 and later, path resolution,
especially for the core library, has become stricter.
Solution
Before importing, it's recommended to define module paths using an importmap within your HTML.
This allows for cleaner and more concise import statements in your JavaScript files.
<script type="importmap">
{
"imports": {
"three": "./javascripts/threejs/build/three.module.js",
"three/addons/": "./javascripts/threejs/examples/jsm/"
}
}
</script>With this importmap, you can import modules simply in your JavaScript files:
import * as THREE from 'three'; // Resolves to "./javascripts/threejs/build/three.module.js"
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; // Resolves to "./javascripts/threejs/examples/jsm/controls/OrbitControls.js"
2. Deprecation of Inline Scripts
In an <script type="module"> environment, directly embedding JavaScript functions within HTML attributes like onclick
or onload is no longer recommended. Functions defined within a module are not exposed to the global scope,
leading to "function not defined" errors when called directly from HTML attributes.
Solution
Remove inline script attributes from your HTML elements and register event handlers
within your JavaScript module using addEventListener.
Before (HTML):
<input type='button' value='BTN' id='IDBTN' onclick='BTNFUNC();'>After (HTML):
<input type='button' value='BTN' id='IDBTN'>JavaScript (within <script type="module"> or a separate .js file):
// Execute initialization code after the DOM is fully loaded
window.addEventListener("DOMContentLoaded", init);
function init() {
// Get the button element
const ELMBTN = document.getElementById('IDBTN');
// If the button exists, add an event listener
if (ELMBTN) {
ELMBTN.addEventListener('click', () => {
BTNFUNC(); // Call the function defined within or imported into the module
});
}
// Add other initialization code here (e.g., Three.js setup)
}
// Definition of BTNFUNC (must be within this module or a properly imported module)
function BTNFUNC() {
console.log("Button clicked!");
}Back to Table of contents
Back to NAS6LIB Repository [Links outside the wiki]