Error in Three.js: THREE.Scene is not defined as a constructor

My code won't run due to this error message:

TypeError: THREE.Scene is not a constructor

I've sourced the three.js file from the official GitHub repository, and these are my files:

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../style.css">
    <title>First three.js</title>
</head>
<body>
    <script type="module" src="../frontend/tetrahedrons_render.js"></script>
</body>
</html>

tetrahedrons_render.js

import * as THREE from '../lib/three.js';
// Create the scene
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x2d3436);
// Set up the camera
const camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 0.1, 1000);
// Set up the render
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Create n random tetrahedrons
const n = Math.floor(Math.random() * 7) + 2;
const tetrahedrons = [];
const positions = [];
let x, y;
for (let i = 0; i < n; i++) {
  do {
    x = Math.floor(Math.random() * 10) - 5;
    y = Math.floor(Math.random() * 10) - 5;
  } while ([x, y] in positions);
  positions.push([x, y]);
  tetrahedrons.push(createTetrahedron(x * 2.5, y * 2.5));
}
// Color one random tetrahedron in black and another in white
const i = Math.floor(Math.random() * tetrahedrons.length);
let i2;
do {
  i2 = Math.floor(Math.random() * tetrahedrons.length);
} while (i2 === i);
tetrahedrons[i].geometry.faces.forEach((face) => {
  face.color = new THREE.Color('black');
});
tetrahedrons[i2].geometry.faces.forEach((face) => {
  face.color = new THREE.Color('white');
});

camera.position.z = 15;

function animate() {
  requestAnimationFrame(animate);
  // Rotation
  tetrahedrons.forEach((tetrahedron) => {
    tetrahedron.rotation.x += 0.03;
    tetrahedron.rotation.y -= 0.03;
  });
  renderer.render(scene, camera);
}
animate();

function createTetrahedron(x, y) {
  const geometry = new THREE.Geometry();
  geometry.colorsNeedUpdate = true;
  geometry.vertices.push(
    new THREE.Vector3(1, 1, 1),
    new THREE.Vector3(-1, -1, 1),
    new THREE.Vector3(-1, 1, -1),
    new THREE.Vector3(1, -1, -1),
  );
  // * To be pointing toward the outside of the cube
  // * they must be specified in a counter clockwise
  // * direction when that triangle is facing the camera
  geometry.faces.push(
    new THREE.Face3(0, 2, 1),
    new THREE.Face3(0, 3, 2),
    new THREE.Face3(0, 1, 3),
    new THREE.Face3(1, 2, 3),
  );
  // Set faces colors
  geometry.faces[0].color = new THREE.Color('red');
  geometry.faces[1].color = new THREE.Color('blue');
  geometry.faces[2].color = new THREE.Color('green');
  geometry.faces[3].color = new THREE.Color('yellow');
  // Set materials
  const material = new THREE.MeshBasicMaterial({
    color: 0x95a5a6,
    vertexColors: THREE.FaceColors,
  });
  material.needsUpdate = true;
  const tetrahedron = new THREE.Mesh(geometry, material);
  tetrahedron.geometry.colorsNeedUpdate = true;
  // Add the tetrahedron to the scene
  scene.add(tetrahedron);
  tetrahedron.position.x = x;
  tetrahedron.position.y = y;
  return tetrahedron;
}

That's the full code, but it seems the issue lies in the first import statement.

I've searched for solutions to this error, but haven't found one that works for me.

Answer №1

When working with Three.js, you will encounter three main output files:

  • three.js
    • This is the un-mangled version of the Three.js source code
  • three.min.js
    • Here you will find a mangled/minified (smaller) version of the bundled Three.js source code
  • three.module.js
    • For those using JavaScript modules, this file contains the Three.js bundle in module format

In order to import the exports from Three.js, it is important to reference the last file mentioned above. Simply copy three.module.js into your lib folder and use the following import statement:

import * as THREE from '../lib/three.module.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

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

I am experiencing some unwanted movement of divs when I hide one element and show another. Is there a way to prevent this from happening

My webpage features a dynamic div that transforms into another div upon clicking a button. Although both divs share similar properties, clicking the button causes some elements to shift unexpectedly. Strangely enough, when the height of the replacing div i ...

Issues with EventListeners in Internet Explorer

Similar Inquiry: Issue with MSIE and addEventListener in JavaScript? I am currently attempting to detect a close event on a popup window created by the parent page. The objective is for users to fill out a form and then, via a popup window, grant perm ...

What is the reason tailwind does not take precedence over locally defined styles?

I've been experimenting with changing the default text color using Tailwind CSS, but for some reason, it's not taking effect. I've noticed that Bootstrap is able to override the default style without any issues. I'm fairly new to Tailw ...

NodeJs and Mysql query execution experiencing significant delays

NodeJs + Mysql query delays and execution timing issue https://github.com/mysqljs/mysql Hello everyone, I'm facing a problem with mysql js. Whenever I use .query(), the callback is taking too long to execute and returning empty results. However, if I ...

What is the best method for retrieving the complete error message from my client-side Node and Express server?

When I send a request to my express route and it returns a 400 status along with an error message, I am facing an issue on the client-side. The alert message only displays "Object object" instead of the actual error message that I see on the server side. U ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

Setting the default <a-sky> in Aframe: A step-by-step guide

There was a fascinating projection I witnessed where two images were displayed in the sky. [https://codepen.io/captDaylight/full/PNaVmR/][code] Upon opening it, you are greeted with two spheres and a default white background. As you move your cursor over ...

Tips for Maintaining Table Headers in Place While Scrolling Through a Table

Check out my jsfiddle: http://jsfiddle.net/7vv9e/2/ In the fiddle, click on the "Add Question" button multiple times until a scroll bar appears next to the table. I am looking to keep the header fixed while scrolling. How can this be achieved? Below is ...

Error encountered while parsing a file: JSON parsing failed due to an unexpected token 'g' at position

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => { console.log('statusCode:', res.statusCode); onsole.log('headers:', res.headers); res.on('data', (d) => { return ...

Manual rotation using the Trackball controls in Three.js allows users to easily manipulate

I am experiencing issues with trackballControls in three.js. My goal is to manually rotate and position the camera. Below is a function I created for testing purposes: function rotateTest(){ console.log(camera.rotation) // THREE.Euler {_x: 0, _y: 0.78 ...

Unable to locate an element on the webpage due to a JavaScript-based error, which then becomes hidden after a few seconds. (Registration form)

While completing a registration form, I encounter a hidden message after clicking on the register button. Struggling to locate this elusive element has been an ongoing challenge for me. Unfortunately, my attempts to find the element have been unsuccessful ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

Utilizing jQuery's Chained Selectors: Implementing Selectors on Previously Filtered Elements

DO NOT MISS: http://jsfiddle.net/gulcoza/9cVFT/1/ LATEST FIDDLE: http://jsfiddle.net/gulcoza/9cVFT/4/ All the code can be found in the above fiddle, but I will also explain it here: HTML <ul> <li id="e1">1</li> <li id="e2" ...

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...

What is the most effective way to retrieve IDs from Firestore and add them to the object arrays?

Currently working on a project that involves React and Firestore, I'm attempting to retrieve the Ids back into the objects array. Below is the code snippet: function grabIds() { setIsLoading(true); reference.onSnapshot((querySnapshot) => ...

jQuery: event not firing for dynamically loaded elements via AJAX

In my jQuery/HTML5 front-end setup (with backend-generated code omitted), I am currently using version 1.8.3 of jQuery with no version conflicts. The front-end calls the following functions: detailAjaxCall("\/client\/orders\/detailsLoad&bso ...

Ionic 2: Image source not being updated

When working with Ionic 2, I encountered an issue where the src attribute of an <img> element was not updating inside the callback function of a plugin. Here is the template code: <img [src]="avatar_path" id="myimg" /> After using the Came ...