What is the Proper Way to Import Three.js Modules in a Vue Application?

My goal is to utilize three.js for displaying a gltf file. To achieve this, I need to import the GLTFLoader module from the three.js node package.

As per the documentation, the correct way to import it is:

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

When I follow this import format, no errors are thrown. Any modification to the path results in a "module not found" error, confirming that the current import method locates the module correctly.

However, upon trying to instantiate the loader based on information provided in the documentation with this line:

var loader = new THREE.GLTFLoader();

I encounter the following error:

GLTFLoader is not a constructor

What am I missing in my implementation?

Despite experimenting with different import approaches, I have been unable to resolve the issue. Most resources reference the same import structure without encountering similar errors. Below is the relevant code snippet within its context.

<template>
    <div id="container"></div>
</template>

<script>
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

export default {
  name: 'ThreeTest',
  data() {
    return {
      camera: null,
      scene: null,
      renderer: null,
      mesh: null
    }
  },
  methods: {
    init: function() {
        var loader = new THREE.GLTFLoader();

        loader.load( 'assets/Models/eames_lounge_chair/scene.gltf', function ( gltf ) {

            scene.add( gltf.scene );

        }, undefined, function ( error ) {

            console.error( error );

        } );

    },
    animate: function() {

    },
    onWindowResize: function() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );
    }
  },
  mounted() {

        this.init();
        this.animate();
  }
}
</script>

<style scoped>
    #container {
        width: 10em;
        height: 10em;
    }
</style>

Answer №1

If you import the loader using this syntax:

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

You don't need to use the THREE namespace when initializing the loader. Simply create it like this:

var loader = new GLTFLoader();

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

Include new items in the li tag using JavaScript

Hello, I am looking to dynamically add elements to an LI element when a link is clicked. I have successfully added elements to a DIV using the following code snippet: I came across a similar question on Which "href" value should I use for JavaScript links ...

jQuery's draggable and resizable functionality with containment provisions is designed to

I'm struggling to create a resizable and draggable div using jQuery, but it's proving to be quite buggy in its implementation. Despite finding similar questions, I haven't come across a solution yet. How can I fix the containment bug when ...

Develop a client-side API utilizing various libraries

After completing the server side of an API that delivers HTML via JSON using REST through CodeIgniter, I am now exploring how to create a client-side API with JavaScript. The goal is to retrieve data from the server through the API, display it in the DOM, ...

Loop through a series of objects using a for loop

I need help with looping through a set of objects using a for loop, but I'm encountering an issue because they do not have the same name. <div id="components-demo"> <div>Travel Information</div> <ul> <li ...

What is the best way to ensure my jQuery plugin is up to date?

I have a question regarding the functionality of this plugin I am using. My goal is to update the timer it provides. To start the countdown timer with 5000 milliseconds remaining, I use the following code: $('#CountdownTimer').countdown({ remai ...

We encountered a sudden termination of JSON data while parsing near '...w2BfLygJAO9ZBvYIqZTld'

Encountered an error when trying to initialize a new React App. command: $npx create-react-app yourblog Node --version v12.16.2 npx --version 6.14.4 Click here to view the error ...

Basic click event triggered every second click in JavaScript and HTML

onclick="HandleAction(\'playnow\');HandleAction(\'stop\');" This element performs two functions simultaneously. However, it only executes the actions \playnow\ and then \stop\ immediately after. ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

Unlocking the variables within a v-for loop post-mounted: A guide to accessing and updating them

I have a question regarding my code snippet below. The calculation of Ending Inventory involves adding the beginningInventory, newInventory, and totalSold values. How can I access the value property of endingInventory in order to update it? Any assistance ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

What's the best way to make a toast notification appear when an API call is either successful or encounters

Seeking guidance on incorporating toast messages within an Angular + Ionic 6 application... My goal is to display a toast message in response to events such as clearing a cart or submitting an order, with the message originating from an API call. While a ...

The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows: <html> <script> <head> var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Troubleshooting NodeJS CORS issue with heavy requests for file uploads

I'm currently working on a project that involves an Angular front end and a NodeJS API deployed in production using AWS services like S3 and Elastic Beanstalk. When attempting to upload images, I encounter a CORS error if the image is too large or wh ...

Vue's Post Request Triggering Data Changes

Encountering a challenge where the data does not update correctly when a new object is included in the array. The current process involves looping through an array of engagements associated with a client as shown below: <div class="row mx-2 px-2 justif ...

Transferring an organized array to processing

My goal is to transfer an array of integers from a php file called load.php to a JS script, which will then forward it to a Processing file written in JavaScript. In load.php, I define the array and send it using JSON (the array contains a minimum of 40 i ...

Nightwatch failing to locate element within iFrame

I'm currently facing a challenge when trying to access an element within an iframe. Despite successfully switching to the frame, Nightwatch keeps returning "element not found" whenever I attempt to verify its presence or visibility. Below is a snippe ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

The Vue.js class bound to the object remains static even after the object is updated

When I have a number of buttons, generated using the v-for directive, with each button having an initial class based on a string from an object. There is an event that changes this string when a button is clicked. However, the class does not get updated a ...