When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a simple scene and am attempting to add orbit controls. However, everything seems to be working fine until I try to import the orbit controls into my main script file, which results in an error message:

Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

Unfortunately, due to my limited experience, I haven't been able to make much progress in solving this issue yet. I have double-checked for any typos and made sure that the relative paths for my imports are correct.

Below is the snippet of code that is currently functioning:

import * as THREE from '/node_modules/three/build/three.module.js';

// import { OrbitControls } from '/node_modules/three/examples/jsm/controls/OrbitControls.js';

// Construct basic scene elements
const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    1,
    1000
);
const renderer = new THREE.WebGLRenderer();
const scene = new THREE.Scene();
// const controls = new OrbitControls(camera, renderer.domElement);

// Set parameters for scene elements
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

As soon as I uncomment the second import statement for the orbit controls, it breaks and shows the error mentioned earlier. Could someone please help me understand what is causing this error and guide me on how to fix it?

Thank you in advance.

Answer №1

If you're looking for an easy solution today:

Simply update the code from

import { OrbitControls } from 'three/addons/controls/OrbitControls';

to
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

Here's where the information comes from:

The last update to three-orbitcontrols was three years ago. It has been deprecated and the message at the top of its npm page reads:

"Author's Message":
The latest versions of three-js now provide real modules accessible via three/examples/jsm/... For instance, to import Orbit, use import { OrbitControls } from 'three/examples/jom/controls/OrbitControls'

Answer №2

Greetings from Stack Overflow! It appears that there might be some missing information in your question, so I will try to make assumptions based on the details provided. If any of my assumptions are incorrect, please update your question with more specifics.

My assumption is that you are including a <script> tag in your HTML to reference your main file, and you are not using JavaScript bundling tools like Mugen87 mentioned. In this scenario, everything seems fine, but it's important to note that OrbitControls won't function correctly unless you make some modifications.

If you delve into the OrbitControls.js file (current as of r.130.1), you'll notice:

import {
    EventDispatcher,
    MOUSE,
    Quaternion,
    Spherical,
    TOUCH,
    Vector2,
    Vector3
} from 'three';

The use of from assumes that you are working within an npm context, not a browser environment. Browsers do not recognize npm packages and cannot resolve three to its node_modules path, resulting in the error message you encountered. To address this issue, you need to adjust the reference to point to the correct module path.

In my view, directly modifying files in the node_modules directory is not ideal. Instead, here's what I suggest:

  1. Create a new folder named
    vendor_mods/three/examples/jsm/controls
    and paste a copy of OrbitControls.js into it.
  2. Modify the reference using from in the copied file to indicate
    /node_modules/three/build/three.module.js
  3. Update the reference in your main file to point to the modified OrbitControls.js.

By following these steps, your browser should be able to recognize all components correctly, ensuring smooth functionality for everyone involved.

Answer №3

After encountering an issue following some updates, my search led me here thanks to Google.

The error message I received was

'Could not resolve 'three/examples/jsm/controls/OrbitControls''

To resolve the problem, I made a simple change:

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

I replaced it with:

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

By adding .js at the end of the import, the issue was resolved.

Answer №4

A handy tool at your disposal is the OrbitControls package, which you can easily integrate using this code snippet:

import { OrbitControls } from "https://threejs.org/examples/jsm/controls/OrbitControls.js";

Answer №5

It is recommended to utilize the threejs package exclusively for importing OrbitControls as advised on the NPM website.

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

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 is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

Eliminating unnecessary gaps caused by CSS float properties

I need help figuring out how to eliminate the extra space above 'Smart Filter' in the div id='container_sidebar'. You can view an example of this issue on fiddle http://jsfiddle.net/XHPtc/ It seems that if I remove the float: right pro ...

Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireB ...

Mirror the content of my div code onto a two-dimensional plane using an A-frame

Query I am currently developing a 3D scene using A-Frame () and I am in need of a solution to mirror an HTML div onto a plane within the A-Frame environment. For instance, imagine a scenario where there is a div at the bottom left corner of the screen fun ...

How to create a Vue.js animated navbar with scroll opacity

I am looking to create a fixed navbar that changes opacity based on user scrolling behavior. Initially, I want the navbar background to be transparent and then transition to white as the user scrolls down the page. An example of what I am trying to achieve ...

Implementing a more efficient method for incorporating UUIDs into loggers

------------system1.ts user.on('dataReceived',function(data){ uniqueId=generateUniqueId(); system2.processData(uniqueId,data); }); ------System2.ts function processData(u ...

Loading Animation with jQuery and Minimum Time Delay

Hello there, I am looking for a way to establish a minimum time duration for an onload function to ensure that a div is displayed for at least 2 seconds. Similar to setting a min-width or min-height, I want the div to be shown for a minimum of 2 seconds e ...

The full height of the image cannot be captured by html2canvas

It baffles me that html2canvas is failing to capture the full height of the div. html2canvas($container, { height: $container.height(), onrendered: function(canvas) { var data = canvas.toDataURL('image/png'); ...

Exploring Javascript's Standard Object: A Guide to Retrieving Two Elements

If I have a special data object: var data = []; data["Name"] = ["Janet", "James", "Jean", "Joe", "John"]; data["Number"] = [25, 22, 37, 19, 40]; Let's say I'm looking for the minimum number value, which is '19' in this case. How ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

What is preventing me from using .bind(this) directly when declaring a function?

Consider the code snippet below: function x() { this.abc = 1; function f1() { alert(this.abc); }.bind(this) var f2 = function b() { alert(this.abc); }.bind(this); } I am curious about how to make the "this" of the out ...

"When utilizing a jQuery AJAX request to communicate with a Node.js server, the functionality only seems to

I'm diving into the world of AJAX and feeling a bit lost. On my webpage, I use an AJAX GET request to fetch comments on a post. However, there's a glitch where the request only succeeds after refreshing the page. I even tried disabling the cache, ...

Step-by-step guide on building a factory in Angular for a pre-existing service

Currently, I am delving into the world of angularjs and exploring articles on service and factory functionalities. One particular example that caught my attention is showcased in this ARTICLE, which includes a demonstration using a Service Fiddle. As I de ...

What is the best way to layer four images in a 2x2 grid over another image using CSS as the background

I am attempting to place 4 images of the same size on a 5th image defined as the background. Currently, it looks like this: It works perfectly when the height is fixed, but in my case, the height may vary causing this issue: This problem isn't surp ...

Node.js: Issues with using async await inside a map function

Currently, I am in the process of developing a clone of Tinder. My focus right now is on working on the match/post request within my backend code. This request involves calling a separate function named match, which is triggered after the current user ha ...

Troubleshooting AngularJS application by Manipulating List Items

Having trouble debugging Angular lately. It feels like things are breaking and fixing themselves magically. For instance, I had an ajax call to delete a "site" which was working fine until I decided to add some code to remove it from the list as well. Now, ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as: react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null a ...