问题描述
我有一个用Typescript编写的类,并且我目前使用的工具是使用tsc生成ES6模块(将文件放置在./dist中)和汇总来创建UMD模块(使用./umd)。两者似乎都产生无错误的输出文件。当前的Typescript代码归结为以下框架:
export class Smokechart {
constructor() {
return this
}
method1() {
return this
}
}
我有一个简单的HTML页面,但是根据选择的选项,我遇到许多不同的错误。当前的HTML代码是:
<script src="http://localhost:3000/umd/smokechart.js" ></script>
<script>
const newChart = new Smokechart()
</script>
最后,浏览器控制台中的错误消息是:
Uncaught TypeError: Smokechart is not a constructor
<anonymous> http://localhost:3000/example/test1.html:18
有什么想法吗?我还能提供什么其他信息?谢谢。
解决方法
回答我自己的问题:有两个问题:
- 我不知道汇总需要为UMD模块提供名称
- 我没有在HTML文件中使用该名称
所以...
a。我需要更改生成UMD文件的汇总命令,以为UMD模块提供--name
:
rollup src/smokechart.ts --file umd/bundle.js --format umd --name Smokechart
b。我需要更改HTML文件以使用。
<script src="http://localhost:3000/umd/bundle.js" ></script>
<script>
const newChart = new Smokechart.Smokechart()
</script>