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

"Embracing AngularJs with the power of SocketIo

Can someone please help me with the code snippet provided below? This code is sourced from: http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets app.factory('socket', function ($rootScope) { var socket = io.connect(); return { ...

Dealing with CORS policy or 404 errors when using Vue.js and socket.io in conjunction with the npm run serve command

I'm currently working on developing my project locally. Running on my local machine is a simple socket.io server: const io = require('socket.io')(); io.listen(3000); In my Vue.js application, I aim to establish a connection with a socket ...

Examining the contents of an array in JavaScript

I am currently conducting API testing. My objective is to verify the presence of a specific name within the API response. The data from the API response is structured in an array format. Despite my intention to check for the existence of the name "activ ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

What is the best way to handle a single promise from a shared listener?

I am working on implementing an event listener that will receive events from a server whenever a specific task is completed. I want to structure each task as a promise to create a more organized and clean workflow. How can I resolve each task promise by i ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

Switching Image Values in JavaScript: A Quick Guide

After successfully using a JavaScript function to swap the src of two images, I encountered an issue. I also needed to switch two values associated with the images so that I could calculate them later. For example: img src="ble.jpg" id="F" value="" onclic ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

Changing the tooltip background color in FullCalendar 6 and Bootstrap 5: A step-by-step guide

My FullCalendar agenda displays events with colored backgrounds. However, I want the tooltips for these events to have matching background colors as well. Currently, the tooltips always show up with a black background. Is there a way to dynamically change ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

What is the method to allocate the smallest available number that has not yet been assigned?

As I'm dynamically generating elements and adding them to the page, each element needs a unique numerical id. However, due to non-linear removal of elements, there can be gaps in the assigned ids. For example... In one scenario: 1, 3, 4, 5, 16, 22. ...

What is the best way to tailor my functions to apply only to specific objects within an array, instead of affecting them all?

I am facing an issue where my functions showMore and showLess are triggering for all objects in the array when onClick is fired. I want these functions to be called individually for each object. Both of these functions are responsible for toggling betwee ...

When text with delimiters is pasted into a Vuetify combobox, why aren't the chips separated correctly by the delimiters?

I'm attempting to create a Vuetify combobox with chips that automatically split the input based on predefined delimiters, such as ,. This means that if I paste the text a,b,c, the component should convert them into three separate chips: a, b, and c. H ...

When you click, transfer a single item from one array to another and modify the text according to the items in the array

How can I dynamically update a shopping cart feature on my website when a user clicks on the "addtocart" button? I want to create functionality where clicking on the button adds the corresponding product to the cart array, and updates the cart amount displ ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

Should we define all public methods or prototype each method separately?

Typically, when I create a library, my approach is as follows: var myLibrary = (function() { return { publicProperty: 'test', publicMethod: function() { console.log('public function'); }, ...

Three.js: Assisting in the creation of a dynamic FlowMap

Currently working on creating a flowmap using Three.js: I've referenced some of the code from this source: https://github.com/mrdoob/three.js/blob/master/examples/webgl_water_flowmap.html however, nothing seems to be displaying on my page: If anyone ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...