typescript - 关于混合commonJS和ES6模块系统的几个问题

标签 typescript ecmascript-6 commonjs

我的问题是关于使用 commonJS(节点样式)和 ES6 模块(使用 typescript )。我有这个 Angular 1.5 应用程序,它使用 commonJS 模块系统。我尝试使用 typescript 来创建应用程序中的工厂之一。几个相同的问题。

  1. 我们可以使用 typescript import 关键字来导入导出的模块吗 使用 commonJS module.exports 语法?例如,假设我们有 我们希望在 typescript 文件中使用下面的 RandomService.js。我 注意到执行 import * as randomservice from “../../services/RandomService.js”引发了一些与不相关的错误 能够找到该模块。我通过使用一个来让它工作 require(),但只是想知道这是否可以在 typescript ?

    var randomString = require('random-string');
    module.exports = {
        getSuperRandom: function() {
            var x = 'super-random-' + randomString();
            return x;
        }
    }
    
  2. 当我们从 typescript 文件导出模块时,通常会导出 对象有一个属性来保存我们的对象。甚至做导出 default 导致 .default 属性具有我们导出的对象。 无论如何,我们可以将导出的对象直接设置为 导出对象(就像我们在 commonJS 模块系统中所做的那样 我们做 module.exports = 'helloservice')?

最佳答案

  1. 是的,可以导入用 javascript 编写的 commonJS 模块,但前提是 Typescript 编译器可以找到 declarations对于这些模块。

例如,如果您在 module1.js 中有此 javascript 模块:

exports.f = function(s) {
    return s.length
}

您必须在文件 module1.d.ts 中提供描述模块并定义其导出类型的声明文件:

export declare function f(s: string): number;

然后您可以通过import使用该模块。如果将此代码放入与 module1.d.ts 同一目录中的 test.ts 文件中,Typescript 将找到导入的模块:

import * as module1 from './module1';

let n: number = module1.f('z');

如果您使用 --module=commonjs (这是默认值)编译此代码,您将得到非常正常的 commonjs 代码:

"use strict";
var module1 = require('./module1');
var n = module1.f('z');
  • 如果您的模块导出一些对象,例如像这样的module2.js:

     module.exports = {
         a: 'a',
         n: 1
     };
    
  • 最好避免使用 es6 语法导入它 - es6 始终假设模块导出命名空间,而不是对象。在 typescript 中,有一种特殊的语法称为 import require为此:

    import m2 = require('./module2');
    
    let n1: string = m2.a;
    

    声明文件module2.d.ts必须使用导出赋值语法:

    export = {} as {a: string, n: number};
    

    实际值 {} 在声明文件中并不重要,可以是任何值 - 只有类型重要(以类型转换的方式给出)。

    如果模块导出一个字符串,如您的示例所示,则声明可以如此简单

    export = '';
    

    关于typescript - 关于混合commonJS和ES6模块系统的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796919/

    相关文章:

    javascript - 使用 Angular (v4) AnimationBuilder 使宽度无响应

    javascript - 如何将 CSS Mixins 应用于原生 Javascript?

    javascript - ecmascript 6 中的 "@"字符是什么意思?

    javascript - 如何获得一个什么都不做的链接

    typescript - 当在对象中保留注释时,代码以一种奇怪的方式编译

    Angular ngFor 使用 map

    javascript - 是否可以在 ES6/7 中导出箭头函数?

    typescript - 从 "@angular"而不是 "angular2"导入 { * }

    javascript - Titanium 项目的正确 CommonJS 结构是什么?

    javascript - 使用模块系统从 HTML 调用 typescript 函数