Problem importing a .glb file using import.meta.url in Three.js using parcel bundler

19 views Asked by At

Hi I startet to make a little Game for me and my Friends with Three.js. I watched many tutorials on how to import .gltf and .glb files. Im using the parcel bundler and the command: npx parcel ./src/index.html to start my project. I am searching for an answer for about 2 months now and i cant find a working solution. My Code is

import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
new GLTFLoader().load( new URL( 'terrain.glb', import.meta.url ), gltf => { 
  let model = gltf.scene;
  model.position.y += 0.48;
  scene.add(model);
});

My Html is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Game</title>
    <style>
        body {
            margin: 0
        }
    </style>
</head>
<body>
    <script src="./js/scripts.js" type="module"></script>
</body>
</html>

and this is my file structure if it helps My Structure

to install three I used: npm install three and to install parcel i used: npm install parcel-bundler --save-dev

when i run it the screen shows nothing and an error shows up: scripts.cd665a19.js:42930 Uncaught SyntaxError: Cannot use 'import.meta' outside a module (at scripts.cd665a19.js:42930:65)

I also tried it like this

const loader = new GLTFLoader();
loader.load('terrain.glb', (gltf) => {
    let model = gltf.scene;
    model.position.y += 0.48;
    scene.add(model);
});

but when i run this it doesent show the 3d object. The error says that a script tag: "<" is missing as far as i know that means that the object is seen as an Html file.

I also tried to remove the type="module" tag from my index.html file because parcel showed an error about the module type but nothing changed.

I really dont know any further and I only have half a year experience with three.js and about a year of experience with js in webdeveloping. Please excuse me if i forgot something this is my first questing on stackoverflow and my english is probably not the best because im from Germany and still only 14yo. Thanks for helping in advance :)

1

There are 1 answers

0
Anton Nagler On

FOUND THE SOLUTION. you need to upgrade to parcel 2 like this: npm install -D parcel
because parcel 2 supports type="module" then you hvae to import your .glb like this:

var url = new URL( 'terrain.glb', import.meta.url );
url = "" + url;

new GLTFLoader().load( url , gltf => {...});