What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tried including "three.module.js" or executing the script as a "module", but both options do not work. Does anyone have a functioning example that they could share with me? The code snippet I am working with is from:

Why does the code work on the provided link but not locally for me?

<script type="module">

    import * as THREE from "lib/three.module.js";
            
    var camera, scene, renderer;            
    var mesh;
            
    init();         
    animate();
            
    function init() {
        camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );                
        camera.position.z = 400;
        scene = new THREE.Scene();
        var geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );                
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00}); 
                
        mesh = new THREE.Mesh( geometry, material );                
        scene.add( mesh );
                
        renderer = new THREE.WebGLRenderer( { antialias: true } );       
        renderer.setPixelRatio( window.devicePixelRatio );              
        renderer.setSize( window.innerWidth, window.innerHeight );      
        document.body.appendChild( renderer.domElement );
                
        window.addEventListener( 'resize', onWindowResize, false );
    }
            
    function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;             
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
            
    function animate() {
        requestAnimationFrame( animate );
        mesh.rotation.x += 0.005;               
        mesh.rotation.y += 0.01;
        renderer.render( scene, camera );
    }
</script>

Answer №1

After conducting thorough research over the past two days, I've discovered that "export / import" only functions through HTTP and not with local directories. This necessitates setting up one's own server. Alternatively, I have opted to use a bundler as Parcel is incompatible with my tablet, but webpack works seamlessly. Setting this up required installing a terminal - in my case, I chose termux. Subsequently, I installed node.js (v12.18.3) via termux followed by webpack. Despite the initial perceived complexity of the process, repetition has made it relatively straightforward. It's crucial to note that Termux must be configured within the Android app manager to access the device's SD card; access is restricted by default, leading to a "permission denied" message when attempting to reach the internal memory with "cd /sdcard/".

The project was created conventionally using an editor without the need for the terminal. Termux is solely used to execute webpack by inputting "npx webpack" after navigating to the project directory.

An example project setup:

//path-structure

webpack-demo
|
|_page.html
|_webpack.config.js
|_src
   |_index.js
   |_bar.js
//page.html
<!doctype html> 
<html> 
<head>  </head> 
<body> 
<div id="message"></div> 
<script src="dist/bundle.js"></script> 
</body> 
</html>

//webpack.config.js
const path = require('path'); 
module.exports = { 
//mode: 'development',
mode: 'production',
entry: './src/index.js', 
output: { path: path.resolve(__dirname, 'dist'), 
filename: 'bundle.js' } 
};
//index.js
import bar from './bar'; 
bar();
//bar.js
export default function bar() { 
 
document.getElementById("message").innerHTML = "Hello World";
}

Software sources:

Termux: available on Google Play Store

Node.js: https://nodejs.org/en/download/package-manager/

Webpack: https://webpack.js.org/guides/installation/

I am now content since I can confidently write well-structured JavaScript code 😁

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

Common JavaScript Framework Startup Errors

Currently, I am delving into the world of JavaScript and experimenting with various thingamajigs. Could someone kindly shed some light on why my script is throwing errors? // Effects object var effects = { // Display an object show : function(obj) { o ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

Guide on invoking a JavaScript function within a jQuery upon a specific event, such as clicking a hyperlink

I have a website page where I display some important information. However, I want to make this text hidden initially and only visible when a user clicks on a specific link or button. I attempted to achieve this functionality using the following code snippe ...

The error message "Cannot read property '$scope' of undefined" indicates that there is an issue

After receiving HTML content in an Angular app, I inject it into the HTML document but struggle to retrieve it. For example, you can see a minimized code on plunker here and in JavaScript here Below is my controller: class ReadCtrl constructor: (@$sco ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

It appears that the jQuery script is not loading properly

For my wordpress site, I have integrated jQuery using the wp_enqueue_script function along with the jQZoom script. In the header of my site, you can find the following lines in this order: <link rel='stylesheet' id='jQZoom_style-css&apo ...

React-select: The default values will only be updated if they are initially set statically

Need help displaying a list of interests from backend data: profile : { interest: ["interest1", "interest2"], }; This is my implementation: import Creatable from "react-select/creatable"; class EditProfileInSettings exten ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...

Tips for including a DOCTYPE declaration when generating an XML document with the "xmlbuilder" npm library

Is it possible to include a !DOCTYPE declaration in an XML file while using the 'xmlbuilder' package? I want to add something similar to the following: <!DOCTYPE IAD.IF.ESTATE.FORRENT SYSTEM "http://www.finn.no/dtd/IADIF-estateforrent71.dtd" ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...

Tips on preventing the occurrence of double encoding in raw JSON output from a view

I am encountering a JavaScript error while attempting to parse JSON data obtained from my controller: Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse () at stores:76 This is the code I use to serialize my list of elem ...

Transform the JavaScript function to a Node.js module

My function serves as an abstract factory for creating JavaScript objects. Here is the code: var $class = function(definition) { var constructor = definition.constructor; var parent = definition.Extends; if (parent) { var F = function ...

How do I add a new module to an existing one using Angular-CLI?

After generating modules: $ ng generate module myTestModule installing module create src/app/my-test-module/my-test-module.module.ts $ ng generate module myTestModule2 installing module create src/app/my-test-module2/my-test-module2.module.ts I ha ...

Detecting changes in input elements when setting values in AngularJS

Access Code: http://jsfiddle.net/mb98y/309/ HTML <div ng-app="myDirective" ng-controller="x"> <input id="angular" type="text" ng-model="data.test" my-directive> </div> <button onclick="document.querySelector('#angular&a ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

Navigate to a specified div using JavaScript

I'm having an issue with my navigation bar not scrolling to the designated div. Despite looking at other examples, I can't seem to find a solution <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> ...

An Ajax GET request will not be able to locate the JSON file

I am having issues retrieving Key and Values from a JSON file using the function provided. Despite placing the 'datafile.json' in the same directory, the code fails to execute the alert(weblink) function, while the alert('test 1') works ...

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...