简体   繁体   中英

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>

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

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

build:{
    transpile:["three"]
}

It was ES6 syntax. Line 6 should look like:

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

ALSO THE REAL ANSWER: https://stackoverflow.com/a/61196076/11896841

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM