【问题标题】:Compiling into CommonJS does not produce files usable by NodeJS编译成 CommonJS 不会产生 NodeJS 可用的文件
【发布时间】:2015-07-17 07:03:19
【问题描述】:

鉴于提供的语法 here(带有导入/导出的标准 ES6 模块)和下面的文件,typescript 编译器 (tsc) 构建的文件在与 NodeJS 一起使用时将抛出 Error: Cannot find module

这是一个精简的例子:


输入文件

src/main.ts

import {Example} from 'example';
let e = new Example();

src/example.ts

export class Example {}

编译

注意,使用来自 Windows 机器的 npm install -g typescript 版本 1.5.0-beta 的 tsc。

tsc --rootDir src --outDir bin

输出文件

bin/main.js

var example_1 = require('example');
var e = new example_1.Example();

bin/example.js

var Example = (function () {
    function Example() {
    }
    return Example;
})();
exports.Example = Example;

我做错了吗?我希望 main.js 包含类似 require('example.js') 的内容。

【问题讨论】:

    标签: javascript node.js typescript ecmascript-6


    【解决方案1】:
    import {Example} from 'example';
    

    您在这里导入的是模块,而不是文件。试试

    import {Example} from './example';
    

    【讨论】:

    • 这当然有效。但是,这似乎与 msdn 链接中提供的内容不匹配。链接不正确,还是我看错了?
    • 可能希望您将子模块安装为模块(链接中的math
    • 可能,不确定。看起来他们正在定义自己的 math.ts 文件。无论如何,感谢您的回复。我可以继续使用这种模式。
    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2022-08-10
    • 2017-11-08
    相关资源
    最近更新 更多