如何在 Nuxt.js 中导入 Three.js OBJLoader?“不能在模块外部使用 import 语句”

Qui*_*sch 2 javascript three.js vue.js objloader nuxt.js

完全菜鸟,需要帮助。

系统:Win 10。浏览器Chrome。框架:Nuxt,默认配置

我通过 npm (通过 gitbash)使用npm install three --save. 它在 package.json 依赖项中为"three": "^0.116.1",。我在 ~/assets/ 中保存了一个 scene.json 文件,该文件是使用Three.js 编辑器> 导出场景生成的。

无论有或没有,我都会收到错误“无法在模块外部使用导入语句”type="module"

这是我正在使用的 Vue 组件:(它仅呈现给客户端。)

<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>
Run Code Online (Sandbox Code Playgroud)

Dac*_*xj0 6

您需要转译 Three.js ES6 模块文件。

将此行添加到 nuxt.config.js 文件中:

build:{
    transpile:["three"]
}
Run Code Online (Sandbox Code Playgroud)