Using webpack, threejs examples, and typescript?

后端 未结 4 1986
逝去的感伤
逝去的感伤 2021-02-02 17:20

I\'m having a lot of trouble getting stuff in threejs\'s examples (like EffectComposer or Detector) to work with webpack and typescript.

First off the relevant *.d

4条回答
  •  悲哀的现实
    2021-02-02 18:13

    I managed to find a pretty clean way to set this up in webpack.config.js.

    As per Dan's answer:

    $ npm install --save-dev imports-loader

    It turns out we don't actually need exports-loader, since the three.js examples add their constructors to the THREE object.

    Then, in webpack.config.js, we can add a rule to add var THREE = require('three'); to an imported module if the module's path resolves to anything containing three/examples/js:

    module: {
      rules: [
        ...
        {
          test: /three\/examples\/js/,
          use: 'imports-loader?THREE=three'
        }
      ]
    }
    

    Now the example modules will find the THREE global when they expect it.

    Then, to make importing examples a little less verbose:

    resolve: {
      alias: {
        'three-examples': path.join(__dirname, './node_modules/three/examples/js')
      },
      ...
    },
    

    This assumes that webpack.config.js is in the same directory as node_modules, adjust accordingly.

    Now, we can use the example files like so:

    import * as THREE from 'three';
    import 'three-examples/controls/OrbitControls';
    

    to import the module for its side-effects.

    If you're using this with Typescript and/or Babel and are getting warnings about the example module not being found on THREE, you may find this issue on the imports-loader repository useful to reference.

提交回复
热议问题