What is the best way to import the three.js OBJLoader library into a Nuxt.js project without encountering the error message "Cannot use import statement outside a module

Beginner here, seeking assistance.

Operating System: Windows 10. Browser: Chrome. Framework: Nuxt with default configurations

I have successfully installed three.js using npm (via gitbash) by running npm install three --save. It is included in the package.json dependencies as "three": "^0.116.1",. Additionally, I have a scene.json file stored in ~/assets/ that was created using the three.js editor and then exported as a scene.

The issue I am encountering is "Cannot use import statement outside a module" regardless of including or excluding type="module"

Here is the Vue component being utilized: (It is rendered client-side only.)

<template>
  <div id="Three">
    <div id="threeContainer"></div>
  </div>
</template>

<script type="module">
import * as Three from 'three'
import OBJLoader from 'three/examples/jsm/loaders/OBJLoader.js'

export default {
  name: 'Three',
  data() {
    return {
      camera: null,
      scene: null,
      renderer: null,
      mesh: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const container = document.getElementById('threeContainer')

      this.camera = new Three.PerspectiveCamera(
        70,
        container.offsetWidth / container.offsetHeight,
        0.01,
        10
      )
      this.camera.position.z = 1

      this.scene = new Three.Scene()

      const loader = new OBJLoader()
      loader.load(
        '~/assets/scene.json',
        function(obj) {
          this.scene.add(obj)
        },
        function(xhr) {
          console.log((xhr.loaded / xhr.total) * 100 + '% loaded')
        },
        function(err) {
          console.error(err.stack)
        }
      )

      this.renderer = new Three.WebGLRenderer({ antialias: true })
      this.renderer.setSize(container.clientWidth, container.clientHeight)
      container.appendChild(this.renderer.domElement)
    }
  }
}
</script>

<style lang="scss">
#threeContainer {
  height: 300px !important;
  background: black;
}
</style>

Answer №1

To properly integrate three.js ES6 module files, transpilation is required.

Simply include the following line in your nuxt.config.js file:

build:{
    transpile:["three"]
}

Answer №2

It utilized the ES6 syntax. At Line 6, the code should be:

import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js'

FURTHERMORE, THE GENUINE SOLUTION IS:

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

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

Receive regular position updates every second in React Native

Currently, my code is functional but lacks reliability. I often encounter delays and sometimes it doesn't update at all. My goal is to achieve real-time position updates. To accomplish this, I have utilized the setInterval() function within the compon ...

The compatibility between V-model and TinyMCE is unreliable

I've been working on integrating Vuejs and TinyMCE, using the @tinymce/tinymce-vue package for the Vue integration. I followed all the instructions and everything seems to be functioning properly - I can write, insert images... everything except for t ...

Following a Node/Npm Update, Sails.js encounters difficulty locating the 'ini' module

While developing an application in Sails.js, I encountered an authentication issue while trying to create user accounts. Despite my efforts to debug the problem, updating Node and NPM only resulted in a different error. module.js:338 throw err; ...

Sending an array of objects over socket io: A step-by-step guide

Recently, I've been struggling with an issue when trying to send an array of objects through socket io. This is my server-side code: var addEntity = function(ent) { entityBag.push(ent); }; var entityBag = []; addEntity(new Circle({ ...

The transfer of JSON information from View to Controller yields no value

My goal is to create functionality where users can add and delete JQuery tabs with specific model data, and then save this data to a database. I'm attempting to use an ajax call to send JSON data to the controller, but I am encountering an issue where ...

using javascript to change a link's state with a click action

I have a question that is related to the topic discussed here: Making a link stay active displaying hover effect upon click using javascript. I am looking for a way to disable the active class when the same link is clicked again. Any assistance on this mat ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Text displayed in dropdown when selecting autocomplete option from Material UI

I'm facing a problem with the Material UI's Autocomplete Component. The issue is that the value is being shown instead of the text element. My data source format looks like this: [{value: 'someValue', text: 'My Text'}, {value ...

Investigating an issue with Vue + vuetify and v-mask integration leading to errors

Utilizing the v-mask package for masking in my Vue component has been successful. <v-text-field v-model="cpfCnpjField" v-mask="maskcpfCnpjField" ></v-text-field> In my testing spec file, I've included the VueMa ...

"Looking to trigger a server click using JQuery or Javascript in your code? Here's how you can

I am facing an issue with triggering a Server-Side OnClick event on an ASP Server Button within a User Control using JavaScript or JQuery. The current methods I have tried do not produce the desired result as they do not actually simulate a user clicking t ...

Access to PHP script (IF) unattainable following a POST occurrence

I'm completely new at this. I am attempting to create a contact form using HTML5 and PHP mail function, but I am facing an issue with my form action pointing to contacto.php. After submitting the form, it seems to be skipping over the IF condition wi ...

Discovering elements with Selenium

While using selenium, I stumbled upon this web element: <td style="padding-right: 10px; " **onclick="javascript:show_me('CarDetails.php?CarID=2358912&SubCatID=1**', '2358912', 560, 'ActiveLinkVisited');stat( '../& ...

What does Event.target.id return - the HTML id value or the HTML name value?

HTML Form Example: <form id="form-product-add" style="display: inline;"> <input name="csrf" type="hidden" value="<?= $this->csrf; ?>"> <input type="hidden" name="a ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code: app.run(function($rootScope,Communications,$http,$filter) { $rootScope.getCommunication = function(object_type ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...

Adjust the color according to the chosen route in a Vue component

I am looking to dynamically change the CSS color based on the route or a prop for a route. For example, if I navigate to the home page, I want the header to be red. If I visit the about page, I want the header to be green. I have attempted this using rout ...

Is there a way to load and play different sounds on multiple audio players based on the length of an array?

I am attempting to load various sounds (.mp3 audio) on separate audio players that are displayed on a single HTML page. The number of players displayed on the screen is determined by the length of the array. In this specific example, I have 3 elements in t ...