如何使用 JSPM 为已导入的库导入其他插件?

How do i import additional plugins for an already imported library using JSPM?

我用 JSPM 成功导入了一个 js 3d 渲染库,如下所示:

import THREE from 'three.js/build/three';

我还想为 Three.js

导入轨道控制插件
import OrbitControls from 'three.js/examples/js/controls/OrbitControls';

但这会引发错误,因为插件没有引用库

Uncaught ReferenceError: THREE is not definedOrbitControls.js:24 (anonymous       function)system.src.js:2187 doEvalsystem.src.js:2153 __evalsystem.src.js:212 asystem.src.js:1019 global.e.metadata.format.e.metadata.executesystem.src.js:540 csystem.src.js:403 ssystem.src.js:715 executees6-module-loader.src.js:1879 oes6-module-loader.src.js:1927 pes6-module-loader.src.js:1701 jes6-module-loader.src.js:1749 kes6-module-loader.src.js:1575 (anonymous function)es6-module-loader.src.js:1177 Oes6-module-loader.src.js:1136 Kes6-module-loader.src.js:927 y.whenes6-module-loader.src.js:818 v.runes6-module-loader.src.js:97 a._draines6-module-loader.src.js:62 draines6-module-loader.src.js:267 b
es6-module-loader.src.js:139 Potentially unhandled rejection [2] Error loading "github:mrdoob/three.js@master/examples/js/controls/OrbitControls" at http://localhost:8080/jspm_packages/github/mrdoob/three.js@master/examples/js/controls/OrbitControls.js
Error loading "github:mrdoob/three.js@master/examples/js/controls/OrbitControls" from "app/main" at http://localhost:8080/app/main.js
Error evaluating http://localhost:8080/jspm_packages/github/mrdoob/three.js@master/examples/js/controls/OrbitControls.js
Uncaught ReferenceError: THREE is not defined (WARNING: non-Error used)

该插件向库中添加了更多功能,如下所示:

THREE.OrbitControls = function ( object, domElement ) { ... }

导入插件的正确方法是什么?

在此示例中,THREE 在其自己的模块范围(ModuleEnvironment,阅读 here)中初始化,而不是全局范围,并且不会被导出。问题是 OrbitControls 在其模块范围内寻找 THREE,然后在全局范围内寻找。因此未找到 THREE 并抛出错误。

你可以用它做什么:

  1. 如果您正在为浏览器编写代码 - 您可以不为不支持它的库使用 es6 模块系统。只需通过脚本标签加载它们并用作全局变量(一如既往,在 es6 之前)。

  2. 可以使用system.js。在那种情况下,您必须配置您的 System 类似:

    System.map['TREE'] = 'three.js/build/three';
    System.meta['three.js/build/three'] = { format: 'global', exports: 'jQuery' };
    System.meta['three.js/examples/js/controls/OrbitControls'] = { deps: 'TREE' }
    

    然后您可以像这样导入这些模块:

    import THREE from 'THREE';
    import 'three.js/examples/js/controls/OrbitControls';
    

关于当前安装的 NPM three.js (0.81.2) :

捆绑文件:three.js

import * as THREE from 'three'; // build/three.js from node_module/three
window.THREE = THREE;
require('three/examples/js/controls/OrbitControls.js');
export default THREE;

然后在你的 index.js

import THREE from './three';