【发布时间】:2018-09-03 07:27:33
【问题描述】:
真的很喜欢 TypeScript,跟着这个简单的sample,最后一部分“导出和导入概念”,砰!首先得到“JavaScript 运行时错误:需要未定义”。谷歌发现我需要安装 RequirJS,有意义,安装,绕过它。现在,'exports' 的相同未定义消息。
这是我经历过的:
-
我浏览了 SO 中的所有 3 个相关帖子, TypeScript Modules in Visual Studio 2015 Update 2 - 'require' is undefined
How to fix '0x800a1391 - JavaScript runtime error: 'require' is undefined'?
Typescript ReferenceError: exports is not defined
仍然没有解决。
添加类似this的TSConfig.json,同样。
下载了应该没问题的源代码,哈哈,他的结尾是
'System' is undefined。 npm 是否安装了 SystemJS,得到“...打开 'C:...\package.json',...没有描述,没有存储库,...,没有许可证。”好的,添加一个空的package.json,结果一样。
所以我的问题是:
- 我自己的项目在这里缺少什么?
- TypeScript 是否需要 TSConfig.json 和 package.json?
我的项目,tsconfig.json:
{
"compilerOptions": {
"noImplicitAny": true,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"node_modules",
"wwwroot"
],
"compileOnSave": true
}
Customer.js
import { Address } from "./Address";
class Customer
{
private _customerName: string = "";
private _addressObj: Address = new Address();
public set CustomerNameBase(value: string){
this._customerName = value;
}
public get CustomerNameBase(){
return this._customerName;
}
Validate()
{
this._addressObj.PlotNumber = 12;
alert(this._addressObj.PlotNumber);
}
}
class CustomerModified extends Customer
{
Validate()
{
throw "throw from CustomerModified";
}
}
Address.ts:
export class Address
{
public PlotNumber: number;
}
Customer.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script src="./Address.js"></script>
<script src="Scripts/require.js"></script>
<script src="./customer.js"></script>
<script>
var customer = new CustomerModified();
try
{
customer.Validate();
}
catch (exception)
{
alert("exception raised: " + exception);
}
finally
{
alert("finally.");
}
</script>
</body>
</html>
【问题讨论】:
-
我认为您正在编写 javascript,就好像它在 node.js 上运行一样,其中 require 和 import/export 是有意义的。您可能希望将所有 javascript 输出编译到 webpack 中。 Webpack 负责转换您的导入和导出,以便它们在浏览器中工作。
标签: typescript