Issue: The import statement cannot be used outside a module for THREE.OrbitControl

Hi there, I've recently started using three.js and encountered some issues while trying to implement orbit controls. Despite its simplicity, I'm stuck on finding a solution for the errors I'm facing. When attempting to add controls like:

var controls = new THREE.OrbitControls(camera, renderer.domElement);

I encounter the following errors:

Cannot use import statement outside a module and THREE.OrbitControls is not a constructor

I made sure to include both Three.js and OrbitControls scripts before starting a new script. Can anyone point out what might be going wrong here?


        <script src="scripts/three.js"></script>
        <script src="scripts/OrbitControls.js"></script>

        <script type="text/javascript">
                var scene = new THREE.Scene();
                var camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight, 0.1, 1000);
                var renderer = new THREE.WebGLRenderer();
                renderer.setSize(window.innerWidth, window.innerHeight);
                renderer.setClearColor(0x888888,1)
                document.body.appendChild(renderer.domElement);
                var controls = new THREE.OrbitControls(camera, renderer.domElement);

Answer №1

Explore the World of Three.js with Online Samples and Code


           <script type="module">
            import * as THREE from 'https://three.samples.com/threejs/resources/threejs/r110/build/three.module.js';
            import { OrbitControls } from 'https://three.samples.com/threejs/resources/threejs/r110/examples/jsm/controls/OrbitControls.js';
            import { OBJLoader2 } from 'https://three.samples.com/threejs/resources/threejs/r110/examples/jsm/loaders/OBJLoader2.js';

            function main() {
.....
</script>

Answer №2

Jest Solution for npm Module Examples

The examples provided in the npm module are not pre-built and would require transformation before use.

Since I'm not actually testing these files, I simply stub them out as follows:

//jest.config.js
  moduleNameMapper: {
    'three/examples/jsm/': '<rootDir/config/jest/mockUndefined.js'
  }

//config/jest/mockUndefined.js
module.exports = undefined

If you do need to involve them in tests, utilizing a ts-jest solution will follow this pattern:

//jest.config.js
{
  //slow preset - does many extra transforms
  preset: 'ts-jest/presets/js-with-ts-esm',
  transformIgnorePatterns: ['/node_modules/(?!(three/examples/jsm)/)'],

Note that the second approach is significantly slower due to jest needing to handle additional file transformations.

Answer №3

My solution involved adding type="module" as suggested by @kaveh-eyni and manually installing the "deprecated" modules into my project.

  • npm install --save three-orbitcontrols
  • npm i --save three-gltf-loader

After that, I made use of:

<script type="module">
import * as THREE from 'three/build/three.module'
import OrbitControls from 'three-orbitcontrols'
import GLTFLoader from 'three-gltf-loader

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

Determine a person's vertical measurement with jQuery

Is there a way to determine the distance from the top of the page to where a link has been inserted? For example, we can use the following code snippet to calculate the height of the window: w = $(window).height(); I am interested in finding out how to ...

Having trouble incorporating a Vue.js element onto a Blade template

I am currently experiencing an issue with loading a Vue.js component on my Blade engine. After adding the Vue.js component, it only loads either the Vue.js 'bootstrap' or the public/js/app.js file depending on what is commented out in the app.bla ...

Integrate a controller using Gulp and Angular

As a newbie to AngularJS, I've embarked on a project using a template named rdas. This template comes equipped with gulp, bower, and node (via npm). Although it's possible that I may have made errors along the way, my current dilemma is creating ...

Create a variable to store the sum value when iterating through a range using jQuery's

Currently, I am in the process of developing a specialized calculator that requires me to calculate the sum of variables within my jQuery.each loop for a specific range from 0 to 4 (equivalent to 5 years). While I have come across several informative reso ...

How come lazy loading isn't functioning in my React project?

Check out my project: link. This project includes routers and lazy-loaded components for each page. Here's a brief example of a router component: export const RoutersComponent = () => { return ( <HashRouter basename={'/'}> ...

What is the best way to implement a dynamic Menu Component in next.js?

Hello friends! I am currently working on a Next.js web app with a Menu Component that fetches data dynamically through GraphQL. I really want to achieve server-side rendering for this menu component. My initial attempt to use getStaticProps() to render the ...

ES6 module import import does not work with Connect-flash

Seeking assistance with setting up connect-flash for my nodejs express app. My goal is to display a flashed message when users visit specific pages. Utilizing ES6 package module type in this project, my code snippet is as follows. No errors are logged in t ...

Troubleshooting three json export glitches in Blender

After installing the three.js plugin for Blender to export models to JSON format, I encountered some issues. When testing with a simple model that only contains colored materials (no textures), I received errors when choosing materials in the options (as s ...

Showcasing information from a database on an HTML page with the use of Node

I am currently attempting to fetch data from my database and display it on an HTML page in a table using EJS for rendering. I found inspiration for my code on this website: Although the database connection is successful, I am encountering difficulties wit ...

Encountered an error with @angular-cli/ast-tools during the installation of angular-cli on a Mac running OS X (El Capitan

While attempting to install the latest version of @angular-cli on my Mac OS X (El Capitan) using the command sudo npm install -g @angular-cli@latest, I encountered the following error: Darwin 15.4.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" ...

waiting for a task to be carried out

Currently, I am working with a function called doSomething() which can be triggered by various DOM events. Is it feasible to listen not just for an event, but for the exact moment when this function is executed? To clarify - I am unable to modify the orig ...

Seeking assistance with creating a custom function to organize arrays within an object

I'm currently attempting to organize an Object that contains only properties which are arrays. My goal is to sort these arrays based on their length in order to ensure that when using Object.keys(), the resulting list will display all names in the cor ...

Fixing trouble with Electron: 'global' ReferenceError happening

Currently, I am developing an Electron application using ReactJS + Bootstrap and Typescript. While attempting to update my Electron version from 11.5.0 to the latest version (15.2.0), I encountered an error message in the developer tools' console: ht ...

Only capitalized keyboard input will be registered by the document on keydown event

I'm currently working on developing a shared canvas wall that looks the same to everyone viewing the webpage and can be edited in real-time by all users. However, I'm facing some challenges when it comes to accurately capturing keyboard input to ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

Spin mesh as the page is scrolled in three.js

Seeking assistance to rotate an object based on page scrolling. Having trouble getting it to function correctly. Currently, this code updates the object's rotation on page load: mesh.rotation.y = window.pageYOffset; However, this only affects the ob ...

A guide on effectively integrating ng-disabled with jade templates

Currently, I am delving into nodejs and experimenting with angularjs for fun. However, I encountered an issue while working on my blog project where I needed to add a file upload feature. After implementing it successfully, I wanted to display the upload b ...

Hide an absolutely positioned div when another element is clicked outside of it

Here is the code for the function that executes when a button on my website is clicked: function displayOverlay() { document.getElementById("overlay").style.visibility = "visible"; document.getElementById("dim").style.visibility = "visible"; d ...

Implementing a feature in jQuery to reveal an element upon button click

I need to create a functionality where clicking a button will display a panel. Initially, I have set the panel's visibility to false in its properties. So, when the user clicks the button, the button should hide and the panel should show up. How can I ...

What is the method to determine the inviter on Discord.js?

Hi there! I'm currently working on an Invite Logger and could use some assistance. I'm having trouble figuring out how to identify the user who invited another user. client.on('guildMemberAdd', async (member) => { const channel = ...