【问题标题】:few questions on mixing the commonJS and ES6 module system关于混合 commonJS 和 ES6 模块系统的几个问题
【发布时间】:2016-11-25 02:37:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: typescript ecmascript-6 commonjs


    【解决方案1】:
    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');
    
    1. 如果你的模块导出了一些对象,例如像这样module2.js:

       module.exports = {
           a: 'a',
           n: 1
       };
      

    最好避免使用 es6 语法导入它 - es6 总是假定模块导出一个命名空间,而不是一个对象。在打字稿中,有一种特殊的语法称为import require

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

    声明文件module2.d.ts必须使用export assignment语法:

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

    实际值{} 在声明文件中无关紧要,可以是任何值 - 只有类型很重要(作为类型转换给未命名的接口)。

    如果一个模块导出一个字符串,就像你的例子一样,声明可以很简单

    export = '';
    

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2018-04-13
      • 2021-11-05
      • 1970-01-01
      • 2013-04-29
      • 2022-12-20
      相关资源
      最近更新 更多