【问题标题】:Typescript and AngularJS 1.5: How to handle export classTypescript 和 AngularJS 1.5:如何处理导出类
【发布时间】:2017-03-30 02:30:14
【问题描述】:

我有这个 module.ts 文件:

import { IHttpService, IPromise } from 'angular';

export class ProductService {
    static $inject = ["$http"];
    constructor(private $http: IHttpService) { }

    loaded: boolean = false;
    promise: IPromise<{ data: any }>;

    getProducts(): IPromise<{ data: any }> {
        if (!this.loaded) {
            this.loaded = true;
            this.promise = this.$http.get('/products.json');
        }
        return this.promise;
    }
}

var module = angular.module("psShopping", ["ngComponentRouter"]);
module.value("$routerRootComponent", "shoppingApp");
module.service('products', ProductService);

这会被转译/编译成 module.js:

"use strict";
var ProductService = (function () {
    function ProductService($http) {
        this.$http = $http;
        this.loaded = false;
    }
    ProductService.prototype.getProducts = function () {
        if (!this.loaded) {
            this.loaded = true;
            this.promise = this.$http.get('/products.json');
        }
        return this.promise;
    };
    ProductService.$inject = ["$http"];
    return ProductService;
}());
exports.ProductService = ProductService;
var module = angular.module("psShopping", ["ngComponentRouter"]);
module.value("$routerRootComponent", "shoppingApp");
module.service('products', ProductService);

有问题的行是:exports.ProductService = ProductService; 如果我手动删除它 - 应用程序可以完美运行。但是,如果我这样离开,在浏览器控制台中我会收到错误“未定义导出”。 关于这个还能做什么?我不能只从 .ts 文件中删除“导出”,因为此类用于其他文件(我将其导入那里)。我尝试了不同的编译器选项,但它只是给了我不同的错误(比如“未定义定义”等),我不知道如何处理这个问题。也许有办法让 tsc 不生产这条线?

【问题讨论】:

  • 你是如何在浏览器中加载模块的?你在使用 browserify/webpack/jspn 等吗???需要导出类吗?
  • 我只有一个附有所有脚本文件的 index.html。我附加的文件之一是上面的文件(module.js)。我的应用中只有一个模块(称为 psShopping)。
  • 在你的 tsconfig 中设置 "module" :"none" 选项
  • 您只能在浏览器中不使用模块加载器的情况下获得这么多。您将只能导入类型,而不是其他模块。
  • 我明白了,是的,现在我得到“当 '--module' 为 'none' 时,不能使用导入、导出或模块扩充。”那么我现在如何修改 module.ts 文件以使其全部工作?或者我可以通过哪些其他方式来完成这项工作(在浏览器中使用模块加载器?)

标签: javascript angularjs typescript


【解决方案1】:

每当您在 typescript 中使用 importexport 关键字时,您就是在将文件转换为模块。

模块设计用于与commonjsamdes6systemjs 等模块系统一起工作...

如果您尝试在浏览器中加载原始脚本而不使用模块加载器或捆绑器,例如 systemjs、webpack、browserify、jspm 等......那么您不能使用外部模块(所以您不能使用进口/出口)。

你仍然可以使用确定类型的类型,但你必须通过///&lt;reference /&gt;标签加载它们。

如果使用 typescript 2.0 类型,如 angular 也可以在运行时默认导入

npm install @types/angular

通常这些类型会公开全局命名空间声明,您现在可以在整个应用程序中使用这些声明。

例如,在您的情况下,angular 公开了一个 ng 命名空间,您可以像这样使用它:

  promise: ng.IPromise<{ data: any }>;

你也可以很容易地给它起别名:

import IPromise = ng.IPromise

请注意,此导入的行为与模块导入的行为不同(它只是别名)。

如果您要做的不是简单的应用程序,我强烈建议您使用模块加载器(例如 webpack)为浏览器编译和捆绑应用程序。仅使用纯脚本有很多限制。

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2015-07-19
    • 2018-07-31
    • 2021-04-14
    • 2021-10-23
    • 2015-08-13
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多