我尝试根据typescriptlang网站重新导出模块 - 我使用SystemJS作为模块加载器的模块:
app.ts
import * as s from "./AllValidators";
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validators: { [s: string]:s.StringValidator; } = {};
validators["ZIP code"] = new s.ZipCodeValidator();
validators["Letters only"] = new s.LettersOnlyValidator();
// Show whether each string passed each validator
strings.forEach(s => {
for (let name in validators) {
console.log(`"${s}" - ${validators[name].isAcceptable(s) ? "matches" : "does not match"} ${name}`);
}
});
AllValidators.ts
export * from "./Validation";
export * from "./LettersOnlyValidator";
export * from "./ZipCodeValidator";
LettersOnlyValidator.ts
import { StringValidator } from "./Validation";
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
Validation.ts
export interface StringValidator {
isAcceptable(s: string): boolean;
}
ZipCodeValidator.ts
import { StringValidator } from "./Validation";
const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<script src="system.js"></script>
<script src="typescript.js"></script>
<script>
System.config({
transpiler: 'typescript',
packages: {
src: {
defaultExtension: 'ts'
}
}
});
System
.import('src/app')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<h1>TypeScript HTML App</h1>
<div id="content"></div>
</body>
</html>
当我在浏览器(Chrome)中运行时,我在控制台日志中看到错误:
答案 0 :(得分:1)
SystemJS未正确检测到Validation.ts中的代码使用es6功能,因此它会跳过编译并尝试按原样加载该文件,从而导致错误。
解决方法是明确声明格式 - 您需要将meta
添加到src
包配置中:
src: {
defaultExtension: 'ts',
meta: {
'*.ts': {format: 'esm'}
}
}
格式为esm
,因为SystemJS没有单独的typescript格式 - 它是相同的es6模块,唯一的区别是它必须由typescript编译器编译(所有支持的模块格式都是documented here)
另一个更丑陋的解决方法是在Validation.ts的开头添加一些虚拟代码,以便正确地自动检测:
export class __SomeUnusedName {}
就够了。