Issue with GLTF Loader Trial: Encountering TypeError when trying to resolve module specifier "three". Invalid references detected; relative references must begin with either "/", "./", or "../"

I'm relatively new to working with three.js and I am currently attempting to load a model into my canvas. However, when I import the GLTFLoader, I encounter the error message mentioned in the console above. Despite checking the syntax and relative paths, everything seems correct and I'm at a loss as to what could be causing the issue. I even tried placing the main three.js folder in another directory but that didn't solve the problem.

import * as THREE from '../master/three.js-master/build/three.module.js'
import {GLTFLoader} from '../master/three.js-master/examples/jsm/loaders/GLTFLoader.js'
const canvas = document.querySelector('.webgl')
const scene = new THREE.Scene()

const loader = new GLTFLoader()
loader.load('../assets/scene.gltf', function(gltf){
  console.log(gltf);
  const root = gltf.scene;
  scene.add(root);
}, function(xhr){
  console.log((xhr.loaded/xhr.total * 100) + "% loaded")
}, function(error){
  console.log('error');
})

// const geometry = new THREE.BoxGeometry(1,1,1)
// const material = new THREE.MeshBasicMaterial({
//   color: 'green'
})

const boxMesh = new THREE.Mesh(geometry,material)
scene.add(boxMesh)

//Boiler Plate

const sizes = {
  width: window.innerWidth,
  height: window.innerHeight,
}

const camera = new THREE.PerspectiveCamera(75, sizes.width/sizes.height, 0.1, 100)
camera.position.set(0,1,2)
scene.add(camera)

const renderer = new THREE.WebGLRenderer({
  canvas: canvas
})

renderer.setSize(sizes.width, sizes.height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
renderer.shadowMap.enabled = true
// renderer.outputEncoding = true
renderer.render(scene, camera)


console.log('working')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Landing Page</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>  
    <canvas class="webgl"></canvas>
    <script type = "module" src="scripts.js"></script>
    <script>
        
    </script>
</body>
</html>

Answer №1

Utilizing ES6 modules such as GLTFLoader in the browser with `r137` requires an import map. Place the following snippet directly below your canvas:

<!-- Import maps polyfill -->
<!-- Remove this when import maps are universally supported -->
<script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80e5f3adedefe4f5ece5adf3e8e9edf3c0b1aeb3aeb6">[email protected]</a>/dist/es-module-shims.js"></script>

<script type="importmap">
    {
        "imports": {
            "three": "../master/three.js-master/build/three.module.js"
        }
    }
</script>

If you have a scripts.js file, make sure to include the three.js import statement like this:

import * as THREE from '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

What could be the reason behind the varying outcomes browsers provide for the JavaScript expression new Date(-105998400000)?

When I use ASP.NET MVC 3 with the default Json serializer, I notice that dates from my JsonResults come back in the format /Date(-105998400000)/. To handle this, I extract the number and create a new Date object with this value. However, I am experiencing ...

Possible rephrased version: "Strategies to halt the playback of a screencast.com video that is

I recently uploaded a screencast video to my website and now I'm looking for a way to pause the video when I click on a button. I attempted using some JavaScript code with an onclick event attached to the button. var myVideoPlayer = document.getEleme ...

Ionic, Angular - A component with two out of three inputs displaying undefined values

I am facing an issue with the @input() in my code. Two out of three inputs have undefined values when I try to use them, although they can be displayed using interpolation in the template file. .ts : export class NoteCanvasPageComponent { @Input() note ...

The Cordova Network Information Plugin is experiencing some functionality issues

I successfully developed a Mobile application using Cordova, Onsen UI, and Vue.js. While addressing network connectivity issues, I incorporated the cordova plugin cordova plugin add cordova-plugin-network-information For determining the type of connectio ...

Issue: Module '../utils/composeObjs' not found after global installation of generator-stencil

Currently, I am in the process of developing a generator for stenciljs which can be found at https://github.com/AkashGutha/generator-stencil Within this project, there is a handy utility function located at the root directory. This function resides in one ...

The VueJS Chosen directive fails to refresh when new options are selected

Struggling to populate my jQuery Chosen dropdown field with AJAX data using VueJS. Unfortunately, when trying to update the values, the Chosen dropdown does not reflect the changes. I've experimented with different approaches, including manually trig ...

What is the best way to make a trail follow my shapes on canvas?

In my current project, I have implemented a feature where shapes are generated by spinning the mouse wheel. One specific shape in focus is the triangle, but other shapes follow the same generation process. The goal is to create a trail that slowly fades ...

What is the reason for requiring this to be passed as an Array instead of a String?

I'm currently learning node.js through a tutorial in a book titled Node Web Developments. Issue: I am struggling with understanding why an array [] is being passed as the 3rd argument from mult-node.js to the required function htutil.page(), instead ...

Retrieving video information using Dailymotion API with JSON and jQuery

I have been struggling to understand the issue even after consulting the Dailymotion API and various sources. I am attempting to retrieve data from Dailymotion for a specific video ID by using the following code: $.getJSON('https://api.dailymotion.co ...

Implement a button transformation upon successful completion of a MySQLi update using AJAX

When displaying multiple database results with buttons that can be turned on or off inside a div, I am looking to implement AJAX to toggle the button state between ON and OFF upon clicking, and then update the button without refreshing or reloading the ent ...

When utilizing backend Node.js with MongoDB, the patch request is unable to successfully update date type values

Using node.js, I have created the backend and integrated MongoDB for data persistence. However, I am facing an issue where I am unable to update the field of date type when making a patch request. Below is the code snippet for handling patch requests in t ...

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...

How to handle a Vue element click event through programming

In my Vue instance, I am looking to have a response triggered by a click on an uploaded thumbnail. Utilizing the Vue package called FineUploader Vue with the template layout as outlined in the documentation (refer to end of question). After uploading an i ...

Utilizing React to pass parent state to a child component becomes more complex when the parent state is derived from external classes and is subsequently modified. In this scenario,

I'm struggling to find the right way to articulate my issue in the title because it's quite specific to my current situation. Basically, I have two external classes structured like this: class Config { public level: number = 1; //this is a s ...

Implement Clip Function with Gradient Effect in JavaScript on Canvas

Trying to incorporate the clip() function within the canvas element to create a unique effect, similar to the one shown in the image. I have successfully achieved a circular clip, but I am now aiming for a gradient effect as seen in the example. How can th ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Enhance the functionality of various textareas by implementing bullets for easier organization and formatting

Is there a way to add bullets to hidden textareas that are created dynamically? Currently, I can add bullets to visible textareas but would like the functionality to extend to newly created ones as well. Additionally, is it possible for these new bullets t ...

Sticky box fails to maintain position as header scrolls

I am looking to create a Sidebar that sticks to the window while scrolling, but stops when it reaches the footer. I have managed to get it partially working, but there is a small issue that I can't seem to solve. Test it live here: Everything seems ...

Unit testing a React component by using the `renderToString` method

Context My React application is built using the React Starter Kit. In the server.js file, components are rendered using renderToStaticMarkup and then passed to the Html component, which includes it using dangerouslySetInnerHTML as shown here. I am facing ...

Retrieve information from an external source and subsequently make alterations to it

If a certain external site returns a string like "cost is 10$", is it possible for me to display it as "price:10$" on my own website using only Javascript? The external site could be something like Facebook.com. My website, of course, belongs to me. Hello ...