使用 Webpack 加载 GLB 模型 - Three.js

Load GLB model with Webpack - Three.js

我是第一次尝试使用 Webpack,我在添加 glb 模型时遇到了问题。我的模型没问题,用了很多次,我放在 public 文件夹里。我不明白控制台错误,任何帮助将不胜感激,谢谢。

我正在使用 three.js r116 和 Firefox。 Safari 告诉我同样的错误,找不到模型。

这是我的 JS 代码的一部分:

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);
    });

我的 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
    }
};

最后控制台错误:

我刚刚发现问题,将这行添加到 webpack.config

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

并且不需要在 public 文件夹中添加资产,它们在我的带有脚本的 src 文件夹中。

我一直在寻找类似的东西,但要寻找 Symfony Webpack Encore 应用程序配置。 @MlleBz 你的回答对我帮助很大,谢谢。 因此,事不宜迟,如果您希望在 Symfony / React / ThreeJS 应用程序中实现 .glb.gltf 加载器,请将其添加到您的 webpack.config.js :

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

对于 Webpack v5,以前的加载器现在已经过时(如 file-loaderraw-loader 等),取而代之的是使用 Asset Modules

gltfobjfbxstl 等 3d 模型格式的正确资产模块是 asset/resource