Having trouble importing the obj loader library in three.js

Attempting to load a 3D object into three.js, I decided to start with the very first basic example in the documentation since I am new to this. Everything seemed fine until I added the import line according to the documentation; suddenly, the scene disappeared and an error appeared in the console:

(index):1 Uncaught TypeError: Failed to resolve module specifier "three/examples/jsm/loaders/GLTFLoader.js". Relative references must start with either "/", "./", or "../"

I simply copied this line from the three.js documentation, so I am unsure why there is an issue with referencing the loader.

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

If anyone can help me understand what went wrong, I would greatly appreciate it. I am using macOS and Atom Live Server for the preview.

Answer №1

Since I am not aware of how your project is structured, you will need to substitute {path} or the file name with the exact static path of the file.

<script type="module">
 import * as THREE from '{path}/three.module.js'
 import { GLTFLoader } from '{path}/GLTFLoader.js'
</script>

If you are not hosting the Three.js file, consider using a CDN

import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three/examples/jsm/loaders/GLTFLoader.js'

EDIT

Understanding NPM and serving files through various server extensions is crucial and may not work automatically. It is recommended to create a single index.html file and directly run it in the browser.

As an illustration, I have replaced all file accesses with CDN links. The initial load may be slow but subsequent runs will benefit from caching.

    <!DOCTYPE html>
<html lang="en">
    <head>
        <title>three.js webgl - glTF loader</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <link type="text/css" rel="stylesheet" href="https://ghcdn.rawgit.org/mrdoob/three.js/dev/examples/main.css">
    </head>

    <body>
        <div id="info">
            <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - GLTFLoader<br />
            Battle Damaged Sci-fi Helmet by
            <a href="https://sketchfab.com/theblueturtle_" target="_blank" rel="noopener"&... [truncated]

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

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

Execute the 'node filename.js' command within a Dockerized environment

Is there a way to run a JavaScript file inside a Docker container automatically every day at midnight? Here is the script for running at midnight, called midnight.sh #!/bin/bash docker exec -it hash_app bash node midnight.js The Docker exec command fu ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...

Update the value in JSON upon the click of a button

Currently, I am dealing with a nested buttonclick situation inside another buttonclick. Right now, my alert is working fine. $scope.getid = function (order) { $scope.chosen.id = order.id; $scope.chosen.status = order.point ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...

When using setTimeout in NodeJS/Express, a TypeError is thrown stating that it cannot read the property 'client' as it is undefined

My nodejs express route is basic: app.get('/timeout', function (req, res) { setTimeout(() => { console.log('timeout'); }, 2000); res.send({ hello: "world" }); }); However, it's not functioning cor ...

the speed of accessing an array in JavaScript

Assuming there is a javascript array1 with 10,000 elements, what would be the time complexity of: var array2=new array(); array2.push(array1); and what about the time complexity of var object={}; object['array2']=array1; Are both operatio ...

The nested router fails to provide the next callback containing the value of 'route'

While developing a middleware handler, I ran into an interesting issue where passing the route string as an argument for the next callback resulted in a value of null. Here's an example to illustrate this: var express = require('express') ...

Issue with handling multiple messages in WebSocket responses as Promises

In my web project using angularjs, I have the task of downloading data every second via a WebSocket. However, I encounter issues with handling multiple requests of different types. Although I utilize Promises to structure the requests, sometimes the respon ...

The set operator in Firestore does not append any new documents to the collection

I recently implemented a promise chain to store user data in Firestore and handle authentication, but I encountered an issue. Initially, I used the add operator to save the data, but later decided to assign users based on their unique UID. After making thi ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

Utilizing three.js to apply a transparent color

Is there a way I can adjust the transparency of vertices based on their color? I want to create areas of varying opacity on a single mesh using the vertColors array. Is it possible to make all vertices of a specific color transparent easily? I'm con ...

The multiple-choice selection tool is not displaying any choices

I am having an issue with my ng-repeat code in conjunction with the jquery multiple-select plugin. Despite using this plugin for a multiple select functionality, the options generated by ng-repeat are not visible. Below is the code snippet in question: & ...

Showcasing a variety of scenarios where resources are being used across several canvases

I am currently working on a project using three.js to develop an interactive web application, but I have hit a roadblock: Within the design, there are numerous canvases enclosed in draggable divs on the page. Each canvas is meant to showcase a 3D object w ...

Creating a dynamic jstree from scratch

My goal is to dynamically generate a jstree when a button is clicked. The user will select the entities from the tree, and I want to display that tree in the selected tab in tree format. The code below works perfectly fine if I use the variable aka as it ...

Merging Objects and inserting them into an array - Harnessing the power of JavaScript and

Having various objects stored in an array, each with a unique labelId assigned to them. Whenever there are matching label ids, the goal is to merge these objects together by consolidating some values inside a new combined object array. [ { fi ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...