Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line

import {GLTFLoader} from "three/addons/loaders/GLTFLoader.js";
into my code, I started encountering a reference error that claimed any function I tried to call was undefined. This issue persisted regardless of where I placed the import statement within the code. I even experimented with loading the import in different sections, but that only led to more errors. Strangely, the error persisted even when the import statement was included within a function that wasn't being called. Does anyone have any insights on where I might be going wrong? Below is a snippet of my code for reference.

import {GLTFLoader} from "three/addons/loaders/GLTFLoader.js";
var soupbowl = soupbowl || {}; //Establishing a namespace
  /*
  Setting up the canvas for a 2D soup animation
  */
  soupbowl.twod = function() {


      var canvasDiv = document.getElementById('soupcanvas');
      canvas = document.createElement('canvas');

      // Determining the canvas dimensions
      let width = canvas.offsetWidth; // Scene width
      let height = canvas.offsetHeight; // Scene height
      canvas.setAttribute('width', 600);
      canvas.setAttribute('height', 600);
      canvas.setAttribute('id', 'canvas');
      canvasDiv.appendChild(canvas);

      if(typeof G_vmlCanvasManager != 'undefined') {
        canvas = G_vmlCanvasManager.initElement(canvas);
      }
      ctx = canvas.getContext("2d");
      //Creating the soupplate
      soupbowl.createPlate();
    }

Appreciate any help!

Answer №1

Make sure to start your file path with "../" to navigate correctly.

For example, in this scenario:

import {GLTFLoader} from "../ three/addons/loaders/GLTFLoader.js";

Avoid using 'var', opt for 'const' instead for better code stability.

Answer №2

Have you made sure to properly include three.js via NPM or a CDN in your project?

To verify, try opening your webpage and typing __THREE__ in the developer console. This will display the current version of the library that is loaded.

If three.js is successfully loaded, here's how you can implement the GLTF loading:

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader();

loader.load(filename, gltf => {

    // Utilize the loaded gltf object here

});

Alternatively, you can use async/await within an async function:

async function initializeScene() {
    
    const gltf = await loader.loadAsync(filename);
    
    // Use the loaded gltf object here
}

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

The processing-js library threw a Reference Error indicating that the Navigator could not be found

I am looking to utilize processingJS as an npm package in a nodeJS server for deployment on MS Azure. I am using VS15 and encountering difficulties referencing it: var pjs = require('processing-js'); var http = require('http'), fs = r ...

How to update newly added information through the existing form in ReactJS

Currently, I am working on a CRUD operation in my project. So far, I have successfully implemented the functionalities to add, delete, and display data. However, I am facing challenges with updating existing data. Despite trying various methods, none of th ...

Having trouble displaying nested JSON data in a DataTable

Hey, I've got a complex JSON array that's pretty nested and minified: { "items" : [ { "track" : { "album" : { "name" : "Pressure Makes Diamonds" }, "arti ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

What steps are involved in setting up a search results page for example.com/s/keyword?

app.js app.get('/results',showResult) var express = require('express') var n = req.query.query; mysql_crawl.query('SELECT prod_name, full_price FROM `xxx` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, p ...

Sorting custom data in a Vue data table, prioritizing null values to be displayed

Currently, in my VueJS v-data-table setup, I am facing a challenge with custom sorting functions. The table has both numeric and string columns, with some null values scattered throughout. My goal is to sort the data by placing null values at the end of ea ...

A step-by-step guide on implementing a callback function

I am eager to incorporate a callback into this script - specifically the third callback onSlideChangeStart(swiper) found at http://idangero.us/swiper/api/#.V9CMp5grJlY. Since I have never worked with callbacks before, I am unsure of where to begin. In es ...

Implementing promises in my MEAN stack application

I have developed a controller that performs a Bing search based on the user's input in the URL. After testing the controller with console.log, it seems to be functioning correctly and I have set the variable to return the results. However, when trying ...

React: When component is suspended, the useEffect hook is not triggered

Exploring the world of react hooks and react suspense has led me to creating a custom hook called useApolloQuery. This hook is designed to fetch data and utilize a promise to wait until the data is loaded. My approach involves placing the data fetching lo ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

Tips for resetting the form input fields in Vue.js after the user has successfully submitted the form

I am facing an issue with my registration page. After the user enters some values and successfully submits the form, I want to clear all the fields. To achieve this, I am using a predefined function called reset() inside the script section. However, the ...

Showing options in the navigation bar upon user authentication with Passport in NodeJS

When a user is connected, I want the navbar to display "Profile of: {USER}", otherwise it should show a set of Sign up/Login tabs. The challenge lies in using EJS with separate "head.ejs" and "header.ejs" sections placed in a /partials folder within the / ...

Trouble arises when attempting to append a class through ng-class upon clicking

In a specific scenario, I am trying to change the border color from black to red in a div by appending a class using ng-class when clicked. However, when clicking a button, the modal opens but the class is not being appended as expected. <div ng-class ...

What is the best way to make the button cover the entire width?

I have a Vuetify card with a layout where I am rendering some dynamic Vuetify components inside the card based on checkbox selection. These components can be a divider, a spacer, toolbar, or a button. However, I'm struggling to make the buttons span t ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

Unable to locate module using absolute import in a Next.js + TypeScript + Jest setup

Currently in my NextJS project, I am utilizing absolute imports and testing a component with Context Provider. The setup follows the instructions provided in this jest setup guide TEST: import { render, screen } from 'test-util'; import { Sideb ...

Ensuring the accuracy of input data in all input fields with the help of dojo

1)In my Dojo widget, I have two additional widgets loaded inside. If I need to clear all text boxes within the widget, I currently use this method: this.myAttachPoint.value="". Is there an alternative code that can achieve the same result without adding ...

An error has occurred in React with a nested JSON object, suggesting that it may actually

I encountered an interesting error with my React file using Axios. While the data retrieval from my post works fine, I am facing a problem when trying to display all posts on one page. Despite my efforts to find a solution, I have not been successful. Bel ...