'How to manually test my typescript library in a browser?
I've some typescript code that creates an svg element that I used in a react project that I'd like to isolate into a separate project which I can distribute on npm.
I'm trying to figure out how to test the library I'm developing. I'm not talking about unit testing but merely load the library in a test html page to see if it works.
I've spent the past few days reading about javascript/typescript modules, bundling tools like webpack, but I'm still confused about how to approach this.
So far, I've managed to write my typescript library in src/lib.ts, and have a separate test/ folder with an html page test/index.html and a simple typescript file test/test.ts that imports my library and then adds the svg element it defines in the html body.
In order for it all to function in a browser so that I can test it, I have webpack bundle test/test.ts into a test-bundle/test.js. The html page actually loads test-bundle/test.js with a <script src="../test-bundle/test.js"></script>
I'd like to know if this looks like a correct way to do it. I'm a bit confused with how to work with typescript in the browser and I'm wondering if I'm taking a convoluted approach to do something simple: call my lib from a browser for testing it.
Solution 1:[1]
Following @Evert's confirmation that webpack is a good way to go, I'm summing up what I learned and the various pieces of documentation that helped me. There aren't that many but it took me a while to figure which were relevant in the volume that is available. I hope this will save time to others.
The root problem is that a barebone typescript library won't run in the browser (see here to find out why and for another way to run typescript in the browser, though only viable for modern browsers). Webpack can help us bundling the library and all it's dependencies so that they run anywhere, like in a browser (included older one which don't support modern module features) or nodejs.
First, webpack's getting started guide shows how to bundle a pure javascript project. Then, webpack also has some documentation to add typescript support.
Finally, the webpack's doc on authoring libraries tells how to bundle a library that you can then import in an html webpage (or anywhere else), and how to use it. The documentation also guides you through keeping your bundle small by not bundling external libraries along with you own lib.
As a bonus, the resulting bundle should be good enough not only for testing but also for being distributed on npm, at which point npm's doc should help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
