Error: The "require" function is not recognized within the Rollup bundle JavaScript file

Recently, I've been utilizing rollup to bundle my JavaScript files designed for integration with three.js. It got me thinking about minimizing and bundling the three.js files using rollup.js as well. To achieve this, I used npm and executed the command npm install rollup three. Here is the content of the index.js file that was created:

import { Scene, PerspectiveCamera, WebGLRenderer } from 'three'

const scene = new Scene()
const camera = new PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10)
camera.position.z = 1

geometry = new BoxGeometry( 0.2, 0.2, 0.2 )
material = new MeshNormalMaterial()

mesh = new THREE.Mesh( geometry, material )
const basic = basicScene()
scene.add( mesh )

const renderer = new WebGLRenderer({antialias: true})
renderer.setSize( window.innerWidth, window.innerHeight )

document.body.appendChild( renderer.domElement )

function animate() {
  requestAnimationFrame(animate)

  mesh.rotation.x += 0.01
  mesh.rotation.y += 0.01

  renderer.render( scene, camera )
}

animate()

The rollup configuration that I used was rollup.config.js:

export default [{
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'cjs'
  }
}]

After running rollup --config, the resulting bundle.js file was generated:

'use strict';var three=require('three');const scene = new three.Scene();
const camera = new three.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 1;

geometry = new BoxGeometry( 0.2, 0.2, 0.2 );
material = new MeshNormalMaterial();

mesh = new THREE.Mesh( geometry, material );
const basic = basicScene();
scene.add( mesh );

const renderer = new three.WebGLRenderer({antialias: true});
renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

function animate() {
  requestAnimationFrame(animate);

  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.01;

  renderer.render( scene, camera );
}

animate();

Upon inspecting the generated bundle.js file, I encountered a couple of issues: 1. The inclusion of require in the bundled script led to a

ReferenceError: require is not defined for rollup
. 2. Additionally, the bundled version didn't seem to be the fully minified rendition of the original JavaScript file.

If anyone could shed some light on the potential reasons behind these problems, it would be greatly appreciated.

Answer №1

If you're using the npm version of three.js and building your project with rollup, there's a minimal sample project that showcases all the essential components for a proper setup:

https://github.com/Mugen87/three-jsm

Here are some comments on your inquiry:

  • It appears that you're not importing all classes from the three package. For instance, BoxGeometry and MeshNormalMaterial are missing.
  • Furthermore, you're referencing the Mesh class via the THREE namespace, which is incorrect.
  • When importing npm packages, rollup necessitates the use of @rollup/plugin-node-resolve.
  • Minification doesn't occur automatically. You'll need to utilize a separate plugin for this, such as rollup-plugin-terser.

Except for the last point, the aforementioned sample project covers all the necessary steps for a proper build.

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

Adding a class to a TD element only when there is text in that TD as well as in other TD elements

I am facing a challenge where I need to add a new class to a td element, specifically the first one in the code snippet below. However, this should only happen if that td contains a certain number (e.g., "2") and if the next td contains some specific text ...

"Hover over the image to see it enlarge and reveal text displayed on top using CSS3

I have been working on creating a responsive image page for my website. I've managed to make the images responsive and centered, no matter the size of the browser window. However, I encountered an issue where when I hover over an image, it enlarges a ...

Instructions for sending a PNG or JPEG image in binary format from a React app to a Node.js server

I am in the process of transferring a file from a react web app to a node.js server. To begin, I have an HTML input of type file where users can upload their files. Once a user uploads a file, a post request is triggered to my Node.js server. Within my N ...

What is the best method to place files from a file input into an array in the Firefox browser?

(I am using Vue 3) I have a functionality where I add files from an input file to an array, and then conditionally render these file names. Everything works perfectly on Chrome, but I encountered an issue with Mozilla Firefox. In Firefox, the array of file ...

Implementing a personalized pipe to enhance search functionality in a data table

I am currently working on a project that involves displaying data in a table. I want to add a search bar functionality that allows users to filter the table data. I have attempted to use a pipe to achieve this, but I am facing challenges and unsure of the ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Retrieve data from a Datatable using jQuery by dynamically generating a click event on a button

Looking to utilize jQuery for the first time, I'm facing an issue accessing the datatable contents upon clicking the erase button. Despite trying various methods, I keep receiving an undefined result. $(document).ready(function() { loadData() }); ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

AngularJS - A Guide to Determining the Time Span Between Two Dates

I am trying to figure out the exact number of months and days between two specific dates. For example, if the start date is "Jan 12, 2014" and the end date is "Mar 27, 2017", the result should be "38 months and 15 days". However, I am currently only able ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...

Use JavaScript or jQuery to implement the position absolute styling

I am currently working on a website where the navigation is aligned to the right side. However, I am facing an issue where the last menu item dropdown extends beyond the page because it is absolutely positioned to the left of its parent element. I am act ...

Having difficulty stripping HTML tags from the response JSON

Hello, I am new to AngularJS and facing an issue with parsing JSON data. The JSON response contains HTML format data, with tags like <, BR, etc. When checking the response in a browser, it appears fine; however, on devices such as tablets or mobile phon ...

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Geometric structures in the style of Minecraft: Hexagonal Voxel Design

I'm attempting to create a hexagonal map by following the example at . Is there a way to generate hexagons instead of cubes? Using the first option from the manual resulted in creating a hexagonal mesh and positioning it. However, the second option ...

Perform a toggle action on the first row when clicking within the current row using Jquery

I've been grappling with the idea of creating a function that can display and hide a comment field when a button is clicked. The challenge here is that there are multiple line items with their own comment boxes. I want to find a way to achieve this wi ...

Transferring a JSON array from Google App Engine to Cloud Storage using GO

I am attempting to upload a JSON array to Google Cloud Storage, which is posted by an App Engine application using the code below: saveData : function saveData() { var _this = this, save = this.shadowRoot.querySelector('#save-data'), ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...