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

Monitoring a folder using webpack

Currently, I have webpack set up in my development environment to bundle all of my dependencies. To help concatenate various js files and include them in a script tag within the markup, I am utilizing the webpack-merge-and-include-globally plugin. Althoug ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

Issue with writing JSON data to a file in node.js

When I try to write JSON objects from the Twitter API to a file using the fs.appendFile method, all that gets written is "[object Object]". The JSON objects look fine when logged to the console, so I'm not sure why this is happening. For example, the ...

Tips for updating data within an array using a copied object

Just starting out with JavaScript Could you assist me with a basic inquiry, please? For instance, I have an array like this: const array = [{ id: 1, name: 'Ferrari', type: 'F40', price: '350 000$', countr ...

Run C# script with the assistance of .load jquery

I have searched extensively for similar posts, but none seem to address the specific question I have regarding my project. What I am attempting to do is load different pages (.aspx) in an iframe dynamically. However, instead of using an iframe, I want to r ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...

Issue with JQuery on Mobile Devices: Troubles with Dropdown Menu and Loading Function

Having some trouble with my JQuery code on mobile devices. The drop down menu isn't showing up on an iPhone, the load function isn't working to display the additional PHP page on a Samsung Edge 7, and the drop down doesn't seem to be functio ...

Tips for seamlessly embedding Youtube iframes within Angular2 components. Resolving issues with unsafe value errors

ERROR: There seems to be an issue in the ./HomeComponent class HomeComponent - inline template:23:84. It is caused by using an unsafe value in a resource URL context. About my homeData model { id: 1, title: '2017 Super Bowl', graphic: 'ht ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Preventing a webpage's CSS from affecting an iframe loading an HTML document

Whenever I load an iframe, it seems to change a bit. Do I need to apply some kind of reset or adjustment? How can I ensure that the content within the iframe looks consistent no matter what page it's loaded into? ...

Seeking the location of the `onconnect` event within the Express framework

With the use of "express," I have implemented a middleware function like so: app.use(function(request, response, next) { console.log(request.headers["user-agent"]); // etc. }); This currently displays the user-agent header in the console for ever ...

Unlocking the Secrets of Laravel Blade Integration in a Script File

I am attempting to create a customized store locator application using the guidance provided in this useful tutorial on Google Maps and Laravel 5. While going through various queries related to integrating Google Maps with Laravel, I came across these info ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Is it possible for a Vuex module to observe or monitor another Vuex module?

Is it possible for Vuex modules to monitor the state of other modules and accordingly trigger actions? Consider this scenario: store.js import time from './store/time' ; import position from './store/position' ; const store = new Vu ...

What is the best way to eliminate an item from an array in JavaScript or AngularJS?

I'm attempting to eliminate objects from an array and retrieve the resulting array. I've been using a remove function, but it's not functioning as expected. Here is the input I'm working with: The goal is to remove all values in the ar ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

I am experiencing issues with my buttons not functioning properly after implementing the fetch API in conjunction with express.js

I'm facing a peculiar issue with buttons that are meant to display templates on the client page. This code is executed on the client side. The primary function of this class is to allow the user to click a button, send a request, receive a response c ...

Issue with VueJs 3 checkbox binding to an array of objects is not functioning as expected

I am struggling to figure out why my v-model is not functioning properly. I have an object called 'service' with a property 'actions' of type IAction[]. Additionally, I have declared an array called actions which also contains IAction o ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

The appearance of Recaptcha buttons is unattractive and seemingly impossible to

Let me start by saying that I have already looked into the issue of "Recaptcha is broken" where adjusting the line-height was suggested as a solution. Unfortunately, that did not work for me. After implementing Google's impressive Recaptcha on my web ...