我尝试使用Typescript使用es6 Set
对象编译多个文件代码,并使用Node.js运行生成的代码。
MyEmitter.ts
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
export {MyEmitter}
index.ts
import {MyEmitter} from "./MyEmitter";
const myEmitter: MyEmitter = new MyEmitter;
myEmitter.on('someEvent', () => { console.log('someEvent occured'); });
myEmitter.emit('someEvent');
const mySet = new Set<number>();
mySet.add(3);
for (let item of mySet)
console.log(item)
编译结果:
$> tsc index.ts
index.ts(13,19): error TS2304: Cannot find name 'Set'.
$> node index.js
someEvent occured
我可以修复&#34;找不到姓名&#39; Set&#39;&#34;编译es6时出错。但是程序现在在运行时出错,在没有es6标志的情况下工作正常:
$> tsc --target es6 index.ts
$> node index.js
./index.js:1
(function (exports, require, module, __filename, __dirname) { import { MyEmitter } from "./MyEmitter";
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
...
我尝试使用行const MyEmitter = require('./MyEmitter');
替换导入的MyEmitter行,但现在tsc错误输出:
$> tsc --target es6 index.ts
index.ts(3,18): error TS2304: Cannot find name 'MyEmitter'.
带有--target es6标志的Typescript是否可以编译在Node.js中可运行的多文件程序?
$> tsc --version
Version 2.8.3
$> node --version
v8.11.1