Three.js fails to load due to Require.js issue

Having encountered a JavaScript error in browser (on the last line mentioned above) with generated code from TypeScript:

define(["require", "exports", "three", "jquery", "./test"], function (require, exports, THREE, jQuery, Test) {
var Main = (function () {
    function Main() {
        this.container = jQuery('#test');
        this.scene = new THREE.Scene();
...

The error message states: Uncaught TypeError: Cannot read property 'Scene' of undefined.

It is interesting that jQuery functions properly while Three.js seems to not be loading at all.

Configurations for requires are as follows:

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    }
});

jQuery is located in the 'js/src' directory, whereas Three.js resides in 'js/three/three.js' (The use of Express hides the js folder from the browser, and relocating three.js to the src folder didn't resolve the issue). Sizzle stands alone due to previous errors when it was placed within a subfolder under src directory.

Am I overlooking something obvious in regards to this issue? I am currently stumped with no clear leads.

Answer №1

Starting from r72

Beginning with r72, the use of define is now required three times. This means you should avoid setting a shim. If your code does not depend on THREE being accessible globally, then you are all set.

However, if there is code that relies on having access to THREE globally, this can pose an issue because as a properly functioning AMD module, THREE no longer leaks into the global space. To address this, you can create a module like the one below to ensure THREE is available globally just before calling requirejs.config:

define("three-glue", ["three"], function (three) {
    window.THREE = three;
    return three;
});

Your RequireJS configuration should include the following map:

map: {
  '*': {
    three: 'three-glue'
  },
  'three-glue': {
    three: 'three'
  }
}

This mapping instructs RequireJS to load three-glue wherever three is needed and vice versa when three is required within three-glue.

All together:

define("three-glue", ["three"], function (three) {
    window.THREE = three;
    return three;
});

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    },
    map: {
        '*': {
            three: 'three-glue'
        },
        'three-glue': {
            three: 'three'
        }
    }
});

(Technical note: Although r72 initially leaked to the global space, some subsequent versions did the same. The most recent version at the time of writing this (r83) no longer has this leakage capability. Using the provided code with an older AMD-compliant version that does leak is safe but results in unnecessary code.)

If using r71 or earlier

If referencing this file, it appears that three does not utilize define. In such cases, you will need a shim to assign a value when requiring it as a module. Here's an example of how to do so:

shim: {
    three: {
        exports: 'THREE'
    }
}

Considering the configuration provided in your question:

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    },
    shim: {
        three: {
          	exports: 'THREE'
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

KnockoutJS's data binding feature is failing to display any content within the table rows

My JavaScript function creates a model and applies it to an HTML document using knockoutJS. In the HTML file, I have two different ways of displaying the same data: 1- A select list (which is working fine) 2- A table (not showing the same data) I need a ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Is it a scope issue if ng-click is not firing and the function is not working properly?

I'm facing an issue with an animation that is not working as intended. The goal is to have the search button trigger an animation to pull a search bar from the right side, allowing users to input their search query. However, the ng-click function does ...

Is it possible to link actions to a storage location external to a component?

Imagine having a store set up with a middleware called redux-thunk. The store is created and exported using the following code: import myOwnCreateStoreMethod from './redux/createStore'; export const store = myOwnCreateStoreMethod(); Now, you ha ...

What methods could I use to prevent the WYSIWYG buttons from automatically linking?

I've been working on creating an editor but I'm facing a small issue. Every time I click on a button (such as bold or italic), it follows a link instead of performing the desired action. Here's a snippet of what I've tried so far: fu ...

"Creating a Miniview Panel on a Fabric Canvas: A Step-by-Step Guide

Is there a way to add a mini view panel to my Fabric Canvas like shown in this image MiniView Panel? I want a panel in the corner of my canvas that displays the entire layout. Similar to the panel on this website . ...

Attempting to recreate the dynamic banner featured in the video

Looking to replicate a setup similar to what was demonstrated in the video. I have two div blocks - one with a random image and the other with a video, and I want them to be as flexible and identical as possible to the video layout. How should I go about a ...

After completing the mapSeries operation, I aim to re-implement the function

How can I return queries (functions) after performing mapSeries? Any help is appreciated! async querys(querys) { const pool = await poolPromise; if (pool != null) { const transaction = new sql.Transaction(pool); ...

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

Establishing a bidirectional binding directive attribute within an AngularJS HTML structure

I'm new to AngularJs and I've encountered a problem that might be due to my lack of understanding about directives, controllers, and isolated scopes. I'm trying to figure out how to set a directive attribute to true/false in the html and kee ...

Obtain user input and showcase it on the screen using a combination of Ajax and PHP

Whenever a user inputs a value in the textbox, it should dynamically display on the screen. I have successfully implemented this feature once, but I am encountering difficulties with implementing it for a second input. Your help is greatly appreciated. fu ...

The animation function in A-frame causes entities to vanish when used with D3.js

Working with the animation property in D3.js has been a bit of a challenge for me. When I include the a-animation directly in the HTML section, everything works as expected. <a-box id="box" position="0 1 0" rotation="0 0 0" scale="1 1 1" color="#4CC3D9 ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Having trouble transferring a PHP string to jQuery

I recently set up a script on my computer that displays a list of active interfaces: $ interfaces eth0 lo wlan0 Now, let me share my PHP code snippet with you: <?php $output=shell_exec('./interfaces'); $string = trim(preg_replace(&ap ...

Firestore Query sends data object to browser

When making a Firestore query, the browser is displaying [object Object],[object Object] instead of the expected output: router.get('/jobopportunities', async(req, res) => { var jobArray = []; const snapshot = await fireba ...

Converting a local Node.js server to an online server: A step-by-step guide

Currently working on a game for my school project. Originally designed to be an online multiplayer game, but have only been able to test it locally so far. Need help figuring out how to modify my server code to make it functional as a legitimate online ser ...

Where is the best place to insert Javascript code in an HTML file - the head or body section?

I am currently developing a search engine and have implemented code to automatically redirect users from HTTP to HTTPS when they visit my site. The only question I have is whether I should place this code in the head or body section of my webpage. if(wind ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Executing Java output to Node.js console using child_process execSync without buffering

Having an issue with the execSync call below: const { execSync } = require('child_process'); ... console.log('Checking Java version') let java_version= execSync('java -version').toString(); console.log('Java version:&apo ...