【问题标题】:Namespace is undefined after compile编译后命名空间未定义
【发布时间】:2016-08-07 23:46:23
【问题描述】:

我正在用 typescript 编写一个小游戏引擎,当我将其编译为 javascript 时,运行 javascript 时出现错误。它编译也没有错误。

我的主入口文件 (ma​​in.ts) 以这两行开头:

require('./core/Obj');
require('./core/Component');

它构建得很好,但是当我运行它时,第二个 require 有一些问题并给出了这个错误:

Uncaught TypeError: Class extends value undefined is not a function or null

核心/Obj.ts

namespace GameEngine {
    export class Obj {
        // Some functions/methods
    }
}

core/Component.ts

namespace GameEngine {
    export class Component extends Obj {
    }
}

然后编译后,它看起来像这样:

(function (exports, require, module, __filename, __dirname, process, global) { (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[
    function(require,module,exports){
        var GameEngine;
        (function (GameEngine) {
            class Component extends GameEngine.Obj { // Error is here
            }
            GameEngine.Component = Component;
        })(GameEngine || (GameEngine = {}));
    },{}],
    5:[function(require,module,exports){
        var GameEngine;
        (function (GameEngine) {
            class Obj {
            }
            GameEngine.Obj = Obj;
        })(GameEngine || (GameEngine = {}));
    },{}]
});

这是我正在运行的 gulp 任务:

gulp.task('compile-engine', function () {
    return browserify()
        .add('./GameEngine/main.ts')
        .plugin(tsify, {})
        .bundle()
        .on('error', function (error) { throw error; })
        .pipe(source('gameEngine.js'))
        .pipe(buffer())
        .pipe(gulp.dest('build/'));
});

【问题讨论】:

标签: javascript typescript browserify tsify


【解决方案1】:

每个模块都有自己的GameEngine 命名空间——因为模块不会污染全局范围。 (在您问题的编译包中,您可以看到它们是分开的。)有一个答案 here 解释了命名空间和模块。

在使用tsify 时,您正在使用(外部)模块。如果您取消命名空间,事情可以变得更简单。 TypeScript Handbook 对使用命名空间和模块有这样的说法:

TypeScript 中模块的一个关键特性是两个不同的模块永远不会为同一个作用域提供名称。因为模块的使用者决定为其分配什么名称,所以无需主动将导出的符号包装在命名空间中。

您可以将导出和导入更改为以下内容:

core/Obj.ts

export class Obj {
    // Some functions/methods
}

core/Component.ts

import { Obj } from "./Obj";
export class Component extends Obj {
}

main.ts

import { Component } from "./core/Component";
// Do something with Component

【讨论】:

  • 我会试试看的。
猜你喜欢
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2011-07-25
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多