javascript - 如何立即使用在 WebStorm 中从 html 生成的 TypeScript?
问题描述
我已经尝试了所有答案,但我遇到了类似的错误
main.js:2 未捕获的 ReferenceError:未定义导出
当我使用编译到 es5 作为目标时
和
Uncaught SyntaxError: Unexpected token {
当我使用编译到 es6 作为目标时
main.ts
import {MyLib} from './mylib';
let myLib = new MyLib("Anonymous", "Someone");
console.warn(myLib);
mylib.ts
export class MyLib {
constructor(public a: String, public b: String) {
}
toString() {
return "library tostring: " + this.a + " " + this.b;
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
索引.html
<html>
<head>
<title>
ts-demo !!
</title>
<script type="module" src="./require.js"></script>
<script type="module" src="./system.min.js"></script>
<script src="./tsdemo/main.js"></script>
</head>
<body>
</body>
</html>
解决方案
- 您需要将
<script>
类型设置module
为使 ES6 模块工作,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="module" src="./tsdemo/main.js"></script>
</head>
<body>
</body>
</html>
- 此外,
.js
在导入时需要扩展以使其在浏览器中工作。Typescript 编译器没有自动添加它的选项(https://github.com/Microsoft/TypeScript/issues/16577),但您可以在main.ts
文件中添加扩展名,例如:
import {MyLib} from './mylib.js';
let myLib = new MyLib("Anonymous", "Someone");
console.warn(myLib);
tsc 做正确的事并从文件中解析类型.ts
,在生成的 javascript 中保留扩展名
推荐阅读
- reactjs - 如何在下面的数据中添加搜索功能(理想情况下在另一个组件中)
- python - 如何通过 Python 中的原始字符串索引将 HTML 标记插入字符串?
- python - 如何使用 selenium 和 Python 从浏览器控制台获取错误和警告?
- c# - 使用属性验证数字中的位数
- tvos - Top Shelf 的 Info.plist 中的 CFBundleDisplayName
- javascript - 蜱的正确定义是什么?
- r - kableExtra::collapse 行干扰 kable(caption = "")
- json - pytest - 访问烧瓶响应参数
- python - Django REST:ViewSet 自定义字典
- bash - 如何在没有前导换行符的情况下在文本文件末尾附加字符串?