Unable to locate module specifier three

Currently, I am working on Three.js in three different modules and using Express as the backend server. In my console, I keep encountering the error:

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

This code snippet below shows the backend code of app.js:

"use strict";
const express = require("express");
const app = express();
const path = require("path");

const port = process.env.PORT || 9000;

app.use(express.static(__dirname + "/public"));

app.use("/build/", express.static(path.join(__dirname, "node_modules/three/build")));
app.use("/jsm/", express.static(path.join(__dirname, "node_modules/three/examples/jsm")));

app.get("/", (req, res) => {
response.send("Connected successfully");
});

app.listen(port, (error) => {
if (error) {
console.warn(`${error} occurred while starting server`);
return;
}
console.log(`listening successfully to the port ${port}`);
});

Moreover, here is a snippet from my javascript file:

import * as THREE from "/build/three.module.js";
import { OrbitControls } from "/jsm/controls/OrbitControls.js";
import Stats from "/jsm/libs/stats.module.js";

// Rest of the JavaScript code has been omitted for brevity...

I have included the javascript file in HTML like this:

<script type="module" src="./client.js"></script>

Here is the visual representation of my folder structure:

https://i.sstatic.net/Mu66m.png

Answer №1

Ensure the browser receives the "importmap" by including a script type importmap in your index.html file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>deore.in</title>    
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body {
            overflow: hidden;
            margin: 0px;
        }
    </style>
    <script type="importmap">
        {
            "imports": {
                "three": "./build/three.module.js",
                "three/examples/jsm/controls/OrbitControls":"./jsm/controls/OrbitControls.js",
                "three/examples/jsm/libs/stats.module":"./jsm/libs/stats.module.js",
            }
        }
    </script>
</head>

<body>
    <script type="module" src="client.js"></script>
</body>

</html>

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

Swapping items within Angular's forEach()

I am working with an array of objects and using a forEach() function in my code. Here is the structure: $scope.things = [ {x: 2}, {x: 4}, {x: 5} ]; angular.forEach($scope.things, function(thing) { //You can uncomment one line at a time ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...

How can I execute a command line utility using JavaScript?

In my latest project, I am developing a JavaScript tool that requires parsing of a password file ('ypcat passwd | grep ') in a Unix environment. Typically in PERL, this can be done using the "backtick" or System to execute command line operations ...

Video playback disabled on hover in Chrome browser

I have added videos to a search results page. When the user hovers over the video, I want to show a preview of it in a separate container and start playing the video. $(".videoSearchResults video").mouseenter(function () { var container = document.cre ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

What is the reason for replace() not working with the word "my"?

Is there a reason why the replace() function in the code snippet below does not replace "my"? $(function() { var str = "put image in my gallery"; str = str.replace(/ my | in /g, " "); }); You can find the code on jsfiddle here. Appreciate any insigh ...

Managing LINK UNLINK actions in Express.js: A guide

I'm currently working on an application that allows GET, POST, and DELETE methods through app.get app.post app.delete However, I have noticed that the verbs LINK and UNLINK are not supported. What is the best way to handle these missing verbs? ...

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

Automated pagination in Jquery running seamlessly

I have successfully created pagination using jQuery. Although the script is functioning properly, I now want it to automatically switch between different pages: <script> $(document).ready(function(){ $("#article_load_favourites").load("indexer_favo ...

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

When using Owl Carousel in Chrome, the carousel unexpectedly stops after switching tabs

Hi there, I'm currently testing out the auto play feature in owl carousel. One issue I've encountered is that when I switch to another tab in Chrome and then return to my webpage with the carousel, it stops functioning unless I manually drag the ...

Creating an AJAX request in Play 2.x by using a shared button

Although I have successfully utilized AJAX requests in the past using a form and adding return false to prevent page refresh, I recently encountered an issue when moving my JavaScript into a separate file. The @ commands now fail, making it difficult for m ...

Unlocking the Power of Angular: Transforming Input into Results

I'm currently exploring how to utilize an input field and fetch a response using Angular directly within the script. As a beginner, I came across this script on codepen. At the end of the code, I've attempted to make a call but haven't compl ...

Establishing the Session Once Headers are Established

Currently, I am working on implementing an asynchronous method that involves making a POST call to a specific API to fetch data and then storing the result in the user's session. Although the task itself seems straightforward, it becomes challenging w ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Guide to storing a PDF document in a MYSQL database using PHP

I am attempting to save all the input information provided by the user in a database. Everything gets saved successfully except for the PDF file. public function insertUM() { if($_POST['um-area']) { $this->usermanual = ...

Issue with toggling functionality on Material UI check boxes when they are printed in a loop

I am attempting to display checkboxes in rows of 4 dynamically, where the number of rows and checkbox values can vary. Below is my JSX code: matrix.map((row, index) => ( <TableRow key={index}> <TableCell al ...

Issue with Socket.io: Server side emit fails to send if the value meets specific criteria

Currently, I am working on a personal project and facing some challenges with socket.io. I am attempting to emit a socket from the server, but it seems that the delivery is only successful if the socket address is changed from /lobby/invalid to /lobby/inf ...

Comprehending the fundamentals of Matrix Operations

I've been struggling with basic matrix transformations and can't seem to grasp it. There's a plethora of outdated code online and I'm unsure of what's current. Here's the snippet I've been working with: var matrixInitia ...