Need assistance as require function is not functioning as anticipated

const THREE = require('three');
require('three/examples/js/loaders/OBJLoader.js');

Once I imported threejs from node_modules, I decided to utilize the provided OBJLoader, but encountered an unexpected error.

THREE is not defined
    at eval (eval at <anonymous> (experiment.js:133), <anonymous>:5:1)

Within the OBJLoader:

THREE.OBJLoader = function ( manager )

The error indicates that Three inside the OBJLoader is not defined even though it was required previously. How should I handle requiring files in this manner?

Answer №1

Utilizing three.js and its code examples can be a bit complex when working with browserify and similar tools due to their reliance on the global variable THREE.

In my browserify projects, I typically create a file named three-loader.js with the following content:

const THREE = require('three');

// Make 'THREE' available globally for example files
window.THREE = THREE;

// Load necessary components from the examples
require('three/examples/js/loaders/OBJLoader.js');

module.exports = THREE;

Throughout the project, I then replace instances of require('three') with

const THREE = require('./three-loader');
.

Alternatively, you can copy the example files into your project directory and add const THREE = require('three'); at the top of each file.

Answer №2

The file

three/examples/js/loaders/OBJLoader.js
does not have a module.exports, so it is not meant to be required in the usual Node.js way. However, you can still require the file as you are currently doing, but keep in mind that it will try to execute the code within that specific file context where the variable THREE is not defined. This file was specifically designed to be loaded in a browser environment where the global variable THREE is defined.

If you want to use Three.js on the client-side, you should include it in your HTML using a script tag:

<script src="js/three.min.js"></script>

This will create the necessary global variable THREE in your browser environment. After including Three.js, you can then load the OBJLoader.js example by adding another script tag:

<script src="js/OBJLoader.js"></script>

Answer №3

When encountering this issue, it is likely due to attempting to load a node module that has not been properly installed. Additionally, missing dependencies related to the module could also result in failure. To resolve this, consider visiting npm and running npm install three, followed by require it in with var three = require('three');.

For more information on npm, visit: https://www.npmjs.com/package/three

In case of the error stated, it indicates the module cannot be found at all. This suggests there may be an issue with the path provided or other dependencies. Typically, running NPM install should rectify any issues. After installation, you can utilize the method on the required object using standard dot notation.

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

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

What could be the reason my dropdown menu is not appearing on hover?

Currently, I am in the process of developing a menu using angularJS and google app script within a dialog box. I have been referring to this sample code for guidance. Instead of pasting all my code here, I can summarize what I have come up with: var a ...

What steps can I take to make sure JSON keys containing only digits are treated as Strings instead of Numbers?

Within a JSON String, I have IDs as keys, represented as Strings of numbers, while the values are actual Numbers (Float). The problem arises when parsing this information to obtain an object in Safari 10.1.2... var jsonData = "{\"53352\":0.6, ...

Steps for implementing a datepicker in a dynamically generated element

Snippet of jQuery code that adds an element to a container $(container).append( '<label class="control-label col-md-3">Join Duration</label>' + '<div class="col-md-4">' + '<input type="text" name="join_dura ...

The communication hub in a Vue.js application

I'm currently developing a Vue single-page project and I have implemented an empty Vue instance as a central event bus. However, I've encountered an issue when trying to fire an event. eventbus.js import vue from 'Vue' export default ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Next JS restricts XLSX to return only 100 objects as an array of arrays

I've developed a file upload system that reads Excel files and uploads data to a database (using Mongoose). After implementing the code, I noticed that when I use console.log(sheetData), it returns an array of arrays with objects inside. Each internal ...

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

ngClass with multiple conditions

I am currently working on implementing the following functionality - I have two pre-set classes that are combined with some component variables successfully. However, I now need to include an additional conditional class. Although the first part is functi ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

As two divs glide across the screen, the top div remains hidden from view

To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images. The bottom image will remain fixed in its position. The middle image should move across the screen. Lastly, the top image will move at a faster ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Versioning resources in Spring MVC with Thymeleaf

https://i.sstatic.net/ArllV.png Struggling with resource versioning in Spring Mvc 4 while using thymeleaf template engine. Despite the code provided, I am unable to see the new version URL when viewing the page source. What could be causing this issue? Wh ...

Guide on downloading jsreport in .Net using C# without opening it

I am using JS Report to generate a file and save it in the root directory. However, I want the file to be downloaded directly instead of opening for viewing. var header = await _jsReportMVCService.RenderViewToStringAsync(HttpContext, RouteData, "H ...

React array mapping issue does not produce any error message

I have exhaustively searched through every answer on Stack Overflow in hopes of finding a solution to my problem. However, I find myself at an impasse as there are no error messages appearing in the console. It seems that there is a hidden bug eluding my d ...

Troubleshooting issue with Django forms and JavaScript interactions

For the past day, I've been grappling with a particular issue and haven't made much progress. My setup involves using a django inline form-set, which displays all previously saved forms along with an additional empty form. To show or hide these f ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...