Utilizing Webpack to Import GLB Models into Three.js

Just delving into the world of Webpack for the first time and I'm encountering some difficulties when trying to add my glb model. The model itself is fine, it's been used multiple times and I placed it in the public folder. I'm puzzled by the console error message, any guidance would be greatly appreciated. Thank you.

I'm currently working with three.js r116 and using Firefox. Safari is also giving me a similar error, stating it can't find the model.

Here's a snippet of my JavaScript code :

import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

const loader = new GLTFLoader();
    loader.load('/assets/models/street_car.glb', (gltf) => {
        scene.add(gltf.scene);
    });

My webpack.config :

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    entry: './src/scripts/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'dist/main.js',
    },
    performance: {
        hints: false
    },
    plugins: [
        new CopyWebpackPlugin([{ from: '**/*', to: '' }], {
            context: 'src',
            writeToDisk: true,
        }),
    ],
    devServer: {
        contentBase: path.resolve(__dirname, 'dist'),
        port: 9000, 
        historyApiFallback: true
    }
};

And here's the console error I'm getting :

https://i.sstatic.net/IQS6F.png

Answer №1

I have successfully identified the issue and resolved it by including the following lines in my webpack configuration:

module:
    {
        rules:
        [
            {
                test: /\.(glb|gltf)$/,
                use:
                [
                    {
                        loader: 'file-loader',
                        options:
                        {
                            outputPath: 'assets/models/'
                        }
                    }
                ]
            },
        ]
    }

Furthermore, I no longer need to add assets to the public folder as they are now located within my src folder along with the scripts.

Answer №2

In the latest version of Webpack, v5, the previous loaders such as file-loader and raw-loader are now considered obsolete. They have been replaced by the implementation of Asset Modules

Specifically for 3D model file formats like gltf, obj, fbx, stl, the appropriate asset module to use is asset/resource

Answer №3

After scouring the internet, I finally found what I was looking for - a solution tailored for a Symfony Webpack Encore application configuration. @MlleBz's answer was like a guiding light for me, and I am truly grateful. Without further delay, for those seeking to incorporate a .glb or .gltf loader into a Symfony / React / ThreeJS application, simply insert the following code snippet into your webpack.config.js:

// add loader for .glb files (use this with three.js)
    .addLoader({
        test: /\.(glb|gltf)$/,
        loader: 'file-loader'
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a promise instance with the axios create method

As someone who is new to TypeScript, I am learning as I go along. One thing I want to do is create an axios instance that can be reused in my code by passing props only where needed. The framework I'm using is React. // Located in a utils folder // a ...

Use the $.get() method in JavaScript to send a parameter to my controller function

My objective is to showcase the event details in a modal. To achieve this, I am running a JavaScript script that calls the "GetEventsDetails" method in my "Event" controller with the event ID. While debugging in Chrome, I can see the ID being passed corre ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Utilizing the power of Vue.js and D3.js in tandem to create dynamic force simulations

Currently, I am attempting to retrieve data from a Restful API call and utilize it to create a d3.js force simulation. However, I have encountered an issue where if I use the data from the API call directly, the simulation treats it as if there is no data ...

I am having trouble globally installing webpack because the terminal is indicating that there is a lack of write access. I have tried enabling the

After enabling the root user and running npm init to create a package.json file, I successfully installed webpack locally in my project using npm i -D webpack. However, attempting to globally install webpack with npm -g i webpack was unsuccessful. Just a ...

What is the best way to retrieve a value from a deeply nested callback function?

I am currently using the mssql npm library and it's functioning well. However, I'm facing difficulty retrieving the recordset returned from the sub-level callback function. Could someone guide me on how to obtain the recordset when dealing with ...

Dynamic JavaScript button control based on time

I am currently working on an app and my goal is to have a feature where the user clicks a button, it will then disappear and only reappear after 24 hours. Here's my progress so far. <div class="buttons"> <p><button onclick="hide(); ...

Is it possible to retract a message on Discord after it has been sent?

I have a code that automatically sends a welcome message when a new member joins the guild, and I want it to be deleted shortly afterwards. Here is my current code: client.on('guildMemberAdd', (member) => { var server = member.guild.id; i ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...

How can I delete the black background from the ion-tab-bar in Ionic 7?

In my current project using Ionic 7, I have a navigation guide set up with 4 tabs. I am trying to customize the styling of these ion tabs by adding some custom CSS. The issue I'm facing is that despite my attempts to make the background transparent, ...

Sorting an array of objects keys according to the position of keys in another array

I have two arrays: one with the correct order of keys and values, and another array coming from a backend in an unsorted format. let arr1 = ['name', 'age', 'occupation', 'address'] let arr2 = [{'age': 20, ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

Difficulty navigating through pages on an iPad due to slow scrolling with JavaScript

My operation is executed within a scroll function, like this: Query(window).scroll(function(){ jQuery('.ScrollToTop').show(); // my operation. }); While my web page responds quickly to the operation, it seems slo ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

How to display a conditional component in a single line with Material UI

I'm facing an issue with a component that is being reused multiple times. Here's the current output: |MyComponent1| |MyComponent2| Specifically, my condition is: if (a == 'One' || b == 'Two'){ <MyComponent data={data}/> ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Activate Bootstrap modal using an anchor tag that links to a valid external URL as a fallback option

To ensure accessibility for users who may have javascript disabled, we follow a company standard of developing our web pages accordingly. Our target demographic still includes those familiar with VCRs blinking 12:00. One particular challenge involves a te ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...