Uncaught TypeError: THREE.MTLLoader is not a const

2019-05-24 04:43发布

问题:

I earlier asked this question in here: Uncaught TypeError: THREE.MTLLoader is not a constructor

Where I got it to work by changing the three-mtl-loader file. But as I am going to upload my work to github later, I have to create a solution without changing these files.

I am therefore instead trying to load in the obj and mtl files using the loaders used in the classic example: https://github.com/mrdoob/three.js/blob/master/examples/webgl_loader_obj_mtl.html

But I still get the error 'Uncaught TypeError: THREE.MTLLoader is not a constructor'

I am a bit unsure about how I would load in these loaders, but right now my code looks like this:

import * as THREE from 'three'
import {OBJLoader} from 'three'
import {MTLLoader} from 'three'


var mtlLoader = new THREE.MTLLoader();
mtlLoader.load("http://blabla.obj.mtl", function(materials) {
   materials.preload();
   var objLoader = new THREE.OBJLoader();
   objLoader.setMaterials(materials);
   objLoader.load("http://blabla.obj", function(object) {

       object.scale.x = scale;
       object.scale.y = scale;
       object.scale.z = scale;

       scene.add(object)

  });
});

Where in the three.js file in the src folder I have inserted:

export { OBJLoader } from './loaders/OBJLoader.js'
export { MTLLoader} from './loaders/MTLLoader.js'

EDIT

I installed using NPM, and the error disappears. Unfortunately other issues occur - but I have asked these in a different question: three-mtl-loader error: THREE.MeshPhongMaterial: .shading has been removed -> object not visible

回答1:

The Three.js docs are misleading. Even though the MTLLoader is in the main documentation, it's actually not part of Three.js's core library. It's included in the examples/ folder of Three.js.

If you're using ES6 module syntax, you have two options.

Option 1: NPM

Usually people publish things like this to NPM because the creators of Threejs don't use modern JS development practices. In this case, there is a three-mtl-loader npm package package.

npm install --save three-mtl-loader

and then

import MTLLoader from 'three-mtl-loader';

Option 2: Copy MTLLoader from Three's source.

You can copy the MTLLoader.js file into your project, but it's not good practice to copy third party libraries into your local project if you're using modern ES6 modules.