Require.js 未加载 Three.js

Require.js not loading Three.js

所以我生成了一些 JavaScript(来自 TypeScript):

define(["require", "exports", "three", "jquery", "./test"], function (require, exports, THREE, jQuery, Test) {
var Main = (function () {
    function Main() {
        this.container = jQuery('#test');
        this.scene = new THREE.Scene();
...

浏览器出现错误(在上面的最后一行):

Uncaught TypeError: Cannot read property 'Scene' of undefined

有趣的是jQuery没有问题;就好像 Three.js 根本没有被加载。

需要配置:

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    }
});

jQuery 位于 'js/src' 文件夹中,而 Three.js 位于 'js/three/three.js' (正在使用 Express,因此 js 文件夹对浏览器隐藏,并且它如果我将 three.js 移动到 src 文件夹似乎没有任何区别)。 Sizzle 是独立存在的,因为它在 src 的子文件夹中导致错误。

我是否遗漏了任何明显的信息?我没有线索

从 r72 开始

从 r72 开始,三个确实调用 define。所以你不应该设置shim。如果您 没有 的代码依赖于 THREE 在全局 space 中可用,那么您就完成了。

但是,如果有 代码依赖于 THREE 在全局 space 中可用,那将是一个问题,因为作为一个行为良好的AMD 模块,THREE 不再只是泄漏到全局 space。对于在全局 space 中需要 THREE 的代码,您可以创建一个这样的模块,您可以在调用 requirejs.config:

之前放置它
define("three-glue", ["three"], function (three) {
    window.THREE = three;
    return three;
});

您的 RequireJS 配置应包含此映射:

map: {
  '*': {
    three: 'three-glue'
  },
  'three-glue': {
    three: 'three'
  }
}

这告诉 RequireJS "wherever three is required, load three-glue instead, but when three is required in three-glue load three."

总计:

define("three-glue", ["three"], function (three) {
    window.THREE = three;
    return three;
});

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    },
    map: {
        '*': {
            three: 'three-glue'
        },
        'three-glue': {
            three: 'three'
        }
    }
});

(技术说明:r72 实际上仍然对全局执行泄漏 space,之后的一些版本也会执行。编辑此答案时最新发布的版本 (r83) not 本身泄漏到全局 space。我没有检查 r72 和 r83 之间的每个版本来检查何时进行了更改。将上面的代码与旧的 AMD 兼容版本一起使用泄漏是否安全。它只会导致不必要的代码。)

对于 r71 及更早版本

如果this file是任意引导,三不调用define。所以如果你希望它在你需要它作为一个模块时有一个值,你需要一个 shim 。像这样:

shim: {
    three: {
        exports: 'THREE'
    }
}

根据您问题中的配置:

requirejs.config({
    baseUrl: "src",
    paths: {
        "main": "../main",
        "test": "../test",
        "three": "../three/three",
        "sizzle": "/src/sizzle/dist/sizzle"
    },
    shim: {
        three: {
            exports: 'THREE'
        }
    }
});