【问题标题】:Typescript namespace can't be found when using Gulp+Browserify使用 Gulp+Browserify 时找不到 Typescript 命名空间
【发布时间】:2017-05-02 17:18:10
【问题描述】:

我一直在一个项目中使用命名空间,一切正常,直到突然找不到这个“测试”命名空间。我错过了什么吗?

Can't find variable: Test in Game.ts

example.ts

namespace Test { 
    export class Example {        
        constructor() {           
            console.log("example");
        }
    } 
}

game.ts

/// <reference path="test/example.ts"/>
namespace Game {
    export class Snippet {    
        constructor() {
            // Test is not found
            let s = new Test.Example();
        }
    } 
}

// Game.Snippet IS found
window.addEventListener("load", () => new Game.Snippet());

更新

经过仔细检查,我认为这是我的 gulpfile 或 browserify 中的错误。当我使用默认的 tsc 操作进行编译时,它可以工作!但是当使用 browserify 时它会失败。我关注了this tutorial

Gulpfile.js

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');

gulp.task("build", function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['dev/main.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .bundle()
    .pipe(source('main.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest("docs/js"));
});

【问题讨论】:

  • 在命令行中添加tsconfig.json或传递给tsc的所有标志。

标签: typescript namespaces


【解决方案1】:

我从您的问题中假设您的文件夹结构如下:

基于此,您可以尝试将参考设置如下

/// <reference path="./test/example.ts"/>

更新

我曾尝试导出命名空间并导入它们。它在离子示例项目中运行良好

example.ts

export namespace Test { 
    export class Example {        
        constructor() {           
            console.log("example");
        }
    } 
}

game.ts

import {Test} from "./test/example"/>
export namespace Game {
    export class Snippet {    
        constructor() {
            // Test is not found
            let s = new Test.Example();
        }
    } 
}

【讨论】:

  • 很抱歉,这没什么区别。我什至把文件放在同一个目录下。
  • 您可能需要使用--outfile 标志将它们全部编译到一个文件中以tsc github.com/Microsoft/TypeScript-Handbook/blob/master/pages/…
  • @AmrElAdawy outFile 完全不相关
  • 我试过把ts编译成一个js,效果很好。
  • 经过仔细检查,我认为这是我的 gulpfile 或 browserify 中的错误。当我使用默认的 tsc 操作进行编译时,它可以工作!但是当使用 browserify 时它会失败。我遵循了本教程:typescriptlang.org/docs/handbook/gulp.html
猜你喜欢
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2021-11-18
  • 2020-02-10
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多