Kenta
Kenta

Reputation: 69

How do I import Three.js into my Nuxt project

I want to import modules in examples folder in THREE.js such as OBJLoader into my Nuxt Project.

I can import main folder of THREE, but error occurs when trying to import modules in examples folder.

Tried these steps in official docs.

https://threejs.org/docs/index.html#manual/en/introduction/Import-via-modules

I'm getting error below

SyntaxError Unexpected token {

<template>
</template>
<script>
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
export default{
}
</script>

here are my github repository https://github.com/ksuhara/threejs-test

Upvotes: 6

Views: 7583

Answers (3)

Claudio Bonfati
Claudio Bonfati

Reputation: 503

Finally I could find what was wrong.

Well, it has to do with nuxt building system. When using third parts libs, you should add them into nuxt.config.js bild->transpile array so it can be included as a dependency with Babel.

transpile: [ "three" ]

Ref: https://nuxtjs.org/api/configuration-build#transpile

Upvotes: 8

Giorgos Lemonidis
Giorgos Lemonidis

Reputation: 61

Finally I managed to do it like this!

<template>
    <div>
        <client-only>
            <threejs-component />
        </client-only>
    </div>
</template>
<script>
export default {
    components: {
        ThreejsComponent: process.browser ? () => import('~/path/to/ThreejsComponent.vue') : null
    }
}
</script>

inside ThreejsComponent.vue are all the threejs imports

Upvotes: 0

Giorgos Lemonidis
Giorgos Lemonidis

Reputation: 61

Threejs must be run on the client side so enclosed the component with <client-only> tag and loaded it dynamically with const MyComponent = () => import('~/path/to/MyComponent.vue'); but now I am getting the error on server side.

Upvotes: 0

Related Questions