【问题标题】:How to get just TypeScript types from threeJs package?如何从 threeJs 包中获取 TypeScript 类型?
【发布时间】:2019-12-05 20:11:18
【问题描述】:

我正在使用包含三个Js 功能的 Webpack 构建前端。过去,我过去常常不在我的包中包含 threeJs 以保持它的小(我使用 index.html 中 CDN 链接中的 threeJs UMD)。不过我确实使用了@types/three 包进行打字。

但是,@types/three 现在已被弃用。相反,three 现在包含其自己的模块化类型。但是现在,如果不将所有大量的threeJs 代码都包含在我的包中,我无法弄清楚如何仅针对其类型使用这三个包。

建议?

【问题讨论】:

    标签: typescript webpack three.js


    【解决方案1】:

    由于您使用的是 Webpack,我的建议是:

    1. 添加three作为项目依赖,这样您就可以继续正常开发并利用包含的类型,然后
    2. 使用 Webpack Externals 将其从与您的应用捆绑的开始排除。

    externals 阻止捆绑某些imported 包,而是在运行时检索它们。

    按照文档示例的相同步骤,您最终会得到类似于以下的设置:

    index.html

    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r106/three.min.js">
    </script>
    

    webpack.config.js

    module.exports = {
      //...
      externals: {
        three: 'three'
      }
    };
    

    这使three 上的所有依赖模块保持不变,即下面显示的代码仍然有效:

    import { Scene } from 'three';
    
    const scene = new Scene();
    

    【讨论】:

    • 啊,是的——很好地考虑外部因素!这很有效,尽管从同一个 npm 包中导入类型化的 OrbitalControls 而不包括主要的 ThreeJs 构建是很棘手的。通过将node_modules/three/examples/jsm/* 目录中的所有内容复制到我的代码库并更改它们的导入路径,我找到了解决该问题的方法。你可以看我的解决方案here
    【解决方案2】:

    它最初已被弃用,但 @types/three 现在可以再次使用。 Moving back to DefinitivelyTyped 于 2021 年 1 月完成。

    所以只需通过运行添加类型

    npm install -D @types/three
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2016-06-03
      • 2019-05-15
      • 2018-08-03
      • 1970-01-01
      • 2023-04-02
      • 2020-04-13
      相关资源
      最近更新 更多