javascriptvue.jsthree.jsnuxt.jsobjloader

How do you import three.js OBJLoader in Nuxt.js? "Cannot use import statement outside a module"


Total noob, need help.

System: Win 10. Browser Chrome. Framework: Nuxt, default configs

I installed three.js through npm (via gitbash) with npm install three --save. It is in the package.json dependencies as "three": "^0.116.1",. I have a scene.json file saved in ~/assets/ that was generated using the three.js editor > export scene.

I get the error "Cannot use import statement outside a module" with or without type="module"

Here is the Vue component I'm using: (It is rendered client-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>

Solution

  • You need to transpile the three.js ES6 module files.

    Add this line to the nuxt.config.js file:

    build:{
        transpile:["three"]
    }