Using CDN to load the STLLoader in Three.js

After deciding to have some fun by creating an STL loader, I've hit a roadblock. Despite trying various solutions found online, I'm still facing issues, mainly due to CDN errors. Currently, I'm following the tutorial on the Three.js site and also referencing this guide.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>STL</title>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <script async src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1772643a7a7873627b723a647f7e7a64572639213924">[email protected]</a>/dist/es-module-shims.js"></script>
    <script type="importmap">
      {
        "imports": {
          "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45312d37202005756b7470716b75">[email protected]</a>/build/three.module.js",
          "stl-loader": "https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0271766e2f6e6d6366677042332c322c32">[email protected]</a>/STLLoader.min.js",
          "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9febf7edfafadfafb1aeaaabb1af">[email protected]</a>/examples/jsm/"
        }
      }
    </script>
        <script type="module">
      import * as THREE from 'three';
      import { STLLoader } from 'stl-loader';

            const scene = new THREE.Scene();
            const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

            const renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            document.body.appendChild( renderer.domElement );

      scene.background = new THREE.Color('#cc0000');

            const loadObject = () => {
        const loader = new STLLoader()
        loader.load("stl_file.stl", function (geometry) {
            group = new THREE.Group()
            scene.add(group)

            const material = new THREE.MeshPhongMaterial({ color: 0xaaaaaa, specular: 0x111111, shininess: 200 })
            mesh = new THREE.Mesh(geometry, material)
            mesh.position.set(0, 0, 0)
            mesh.scale.set(10, 10, 10)
            mesh.castShadow = true
            mesh.receiveShadow = true

            geometry.center()
            group.add(mesh)
        })
      } 

      loadObject();
            camera.position.z = 5;

      renderer.render( scene, camera );
        </script>
    </body>
</html>

The majority of the code was sourced from here, as mentioned earlier. However, upon checking the console, I encountered this error message:

Uncaught SyntaxError: The requested module 'stl-loader' does not provide an export named 'STLLoader'
. This issue is just one of several that I need to address...

Answer №1

If you're trying to import the STLLoader.min.js file as an ES6 module, it won't work since it's not designed that way. To successfully import it using ES6 syntax, ensure that the file has a structure similar to the STLLoader module in the three npm package:

Check out the correct structure here.

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

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

What is the best way to divide an array into pairs and store them in separate arrays?

I'm attempting to challenge my JavaScript skills and faced with a dilemma. There is an array containing data var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];. The goal is to pair the elements and generate a new array of arrays such as var newArray = [[1 ...

Master the art of filtering rows in an HTML table based on a select option when the mouse is clicked

I am trying to create a table that displays only the rows selected in a dropdown menu. Here is an example: If "All" is selected, the table should display all rows. If "2017" is selected, the table should display only the rows that have "2017" in the sec ...

Creating a dynamic className string in JavaScript with React

In my current project, I'm implementing mobile support by creating separate styles for desktop and mobile. Although most components are the same on both platforms, I have two .scss files dedicated to each. To apply the correct styles, I use a combina ...

Shader in THREE.js designed to accommodate ControlNet for normal calculations

Is there a way to adjust this standard shader to bypass the preprocessor for controlnet? Check out the code here: https://jsfiddle.net/lunchie/mpuanxL3/4/ skinnedMesh.material = new THREE.ShaderMaterial( { vertexShader: [ '# ...

A method for transforming each word in a string to begin with a capital letter

I'm not sure if my approach to solving this problem is correct: function capitalizeFirstLetter (string) { let stringArray = string.split(' '); for (let i = 0; i < stringArray.length; i++) { let firstLetter = stringArray[i ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...

Script execution in '<URL>' has been prevented due to sandboxing of the document's frame and the absence of the 'allow-scripts' permission setting

When I deploy my pure Angular application with a REST API to a production server and try to access its URL from another site (such as a link in an email), I encounter a strange problem. Firefox doesn't provide any error message, but Chrome says: Blo ...

Adding a border to the <area> element: A step-by-step guide

Can a border be added around an <area> element? This would be useful for testing an imagemap, however the following code does not achieve the desired effect: area { outline: 1px solid red; border: 1px solid red; } ...

Difficulty encountered when applying a CSS class with JavaScript

The Javascript function I am currently using is able to select multiple links. This behavior occurs because of the Regular expression I applied with the '^' symbol. I decided to use this approach because my links are in the following format: htt ...

Is it possible to set functions as variables within an if statement in JavaScript and then not be able to call them later?

My validation process involves a multi-function where I don't invoke a master function beforehand to check and validate inputs. Within my "SignUp Function", I have implemented a validation function as variables that are checked before passing to the r ...

Saving modified input data for submission using Vue

Objective: The main goal is to have a form interface loaded with an object's current data for editing. This allows the user to open a modal with the form already filled out with the existing information, giving them the option to either edit it or lea ...

"Failure to Update: Ajax Auto-Refresh Table Failing to Refresh

I'm facing a tricky issue with my code that I just can't seem to resolve. Currently, I am using Ajax and setTimeout to retrieve data. The problem arises when the data doesn't refresh automatically (if I manually navigate to the page getdata. ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Find and filter the values in the range.getValues() array that correspond to the first element in apps script

In the spreadsheet provided, I have compiled a list of cities in different states of my country. This information will be utilized in a form; however, it is not feasible for users to sift through an extensive list of all cities listed. Therefore, I am look ...

Unable to input characters consecutively into the text field because it is being displayed as a distinct function within the component

When attempting to bind a text field using the approach below, I encounter an issue where entering characters in the text field causes the control/focus to shift out of the field after the first character is entered. I then have to click back into the text ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Verification of email address is required, emails must be unique and not duplicated

I am working on validating email addresses to ensure they are not repeated. So far, I have successfully pushed them from the server into an array using regex for validation. What steps should I take next to compare and further validate these emails? ...

Implement a Basic Custom Shader on a Cube in Three.js

Struggling with applying a basic custom shader to a cube in Three.js. Whenever I attempt to use the shader, the cube mysteriously vanishes. No issues when using a standard Toon or Lambert Material - cube rotates and behaves as expected. Oddly, Orbit Contr ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...