create account

External modules without bundling in typescript by smjn

View this thread on: hive.blogpeakd.comecency.com
· @smjn · (edited)
$0.58
External modules without bundling in typescript
Last week I finished the [Preact-cli template](https://busy.org/@smjn/preactubats-preact-cli-template) and this week I begun on a project to make use of that template. I've decided to make a new website for [spelmakare.se](https://spelmakare.se) as practice before doing an actual new project using the template.

## Background for today's problem
I wanted to be able to use external modules (such as [dsteem](https://jnordberg.github.io/dsteem/)) without the need to actually bundle the whole module with my own scripts. I've made attempts at this in the past and always had issues getting it to work consistently. 

When creating the production script you can define modules you do not want included, and then those modules can be added externally with <script> tags in the html. The benefit is that you get a smaller script file for your site and that the module can be loaded from a distributed network, like [cdnjs](https://cdnjs.com/). The last bit is beneficial in particular, because if you have visited one site with a lib that another site also uses, in many cases your browser can use the cached file you already have from the first site. 

This whole excluding thing is what has caused me issues in the past. Possibly because of my limited knowledge, but the result none the less the same... a day spent solving a technical issue like this, instead of swiftly making an actual project. If I got one module working, then the next has had some sort of failure and so forth.

Today I decided to get this solved.

## Today's solution
After doing some research I cooked up this solution that fits my needs. It is easy to use, gives you full [Intellisense](https://code.visualstudio.com/docs/editor/intellisense) when writing code and seems to be consistent in functionality.

I'm using dsteem as an example.
    
    $npm install dsteem

We will not actually use dsteem in the code, we only install it to get the declarations. There are other ways to do this, but this is quick, simple and has no impact except increasing the file size of our node_modules folder a bit.

First we create a helper function to use when loading external scripts. You give the script tag an unique ID and the url to the script file. An event listener is configured and a callback will trigger as soon as the script file has finished loading.
    
    /**
     * Load external script files to avoid bundling.
     * 
     * @param scriptID string for tag ID.
     * @param scriptSrc url to script file.
     * @param callBack callback function to be triggered when script file loaded.
     */
    export function extScriptLoader(scriptID: string, scriptSrc: string, callBack: any) {

        // Append script if none exists.
        if (document.body.querySelector("#" + scriptID) === null) {

           // Callback when script loaded.
           let finishedLoading = () => {
                callBack();
                document.getElementById(scriptID).removeEventListener("load", finishedLoading);
            }

            let script = document.createElement("script");
            script.id = scriptID;
            script.src = scriptSrc;
            document.body.appendChild(script);

            document.getElementById(scriptID).addEventListener("load", finishedLoading);
        }

        // Callback directly as script already exists.
       else {
            callBack();
        }
    }

In the script file where we will use dsteem. First we declare dsteem (making use of what we installed earlier) to get Intellisense working, and then use the helper to load the script
    
    declare const dsteem: typeof import("dsteem");

    extScriptLoader("steemScript", 'https://unpkg.com/dsteem@^0.10.1/dist/dsteem.js', () => {
        this.createClient();
    });

createClient is only a test function I've done to check so this works, it looks like this:
    
    async createClient() {
        this.client = new dsteem.Client("https://api.steemit.com");

        const accounts = await this.client.database.getAccounts(["smjn"]);

        accounts.forEach(account => {
            document.getElementById("newsItem").innerHTML = account.name;
        });
    }

Visiting the page it will check for the unique script ID, if none found, it will append the script tag to the body and the script file gets downloaded. When done it calls back and that triggers the fetching of my Steem account and when ready it updates the "newsItem" to contain the name of my account.

![moduleloading.gif](https://ipfs.busy.org/ipfs/QmbBMwGWmMThJJvUhKyFJAeBiAVMDc7nUXiWLWPhyYayh1)

Thanks for reading!
👍  , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorsmjn
permlinkexternal-modules-without-bundling-in-typescript
categorydevelopment
json_metadata{"community":"busy","app":"busy/2.5.6","format":"markdown","tags":["development","javascript","busy","smjnblog"],"users":["smjn","param"],"links":["https://busy.org/@smjn/preactubats-preact-cli-template","https://spelmakare.se","https://jnordberg.github.io/dsteem/","https://cdnjs.com/","https://code.visualstudio.com/docs/editor/intellisense"],"image":["https://ipfs.busy.org/ipfs/QmbBMwGWmMThJJvUhKyFJAeBiAVMDc7nUXiWLWPhyYayh1"]}
created2018-10-22 12:42:18
last_update2018-10-22 12:51:36
depth0
children3
last_payout2018-10-29 12:42:18
cashout_time1969-12-31 23:59:59
total_payout_value0.444 HBD
curator_payout_value0.134 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,586
author_reputation8,662,132,469,561
root_title"External modules without bundling in typescript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,813,196
net_rshares498,227,158,671
author_curate_reward""
vote details (21)
@steem-ua ·
#### Hi @smjn!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your **UA** account score is currently 1.824 which ranks you at **#28640** across all Steem accounts.
Your rank has dropped 154 places in the last three days (old rank 28486).

In our last Algorithmic Curation Round, consisting of 299 contributions, your post is ranked at **#288**.
##### Evaluation of your UA score:

* Only a few people are following you, try to convince more people with good work.
* Your contribution has not gone unnoticed, keep up the good work!
* Try to work on user engagement: the more people that interact with you via the comments, the higher your UA score!


**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-external-modules-without-bundling-in-typescript-20181022t194112z
categorydevelopment
json_metadata"{"app": "beem/0.20.7"}"
created2018-10-22 19:41:12
last_update2018-10-22 19:41:12
depth1
children0
last_payout2018-10-29 19:41:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length787
author_reputation23,214,230,978,060
root_title"External modules without bundling in typescript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,837,534
net_rshares0
@steemitboard ·
Congratulations @smjn! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@smjn/votes.png?201811182103</td><td>You made more than 3000 upvotes. Your next target is to reach 4000 upvotes.</td></tr>
</table>

<sub>_[Click here to view your Board of Honor](https://steemitboard.com/@smjn)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemfest/@steemitboard/meet-the-steemians-contest-special-attendees-revealed"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmeLukvNFRsa7RURqsFpiLGEZZD49MiU52JtWmjS5S2wtW/image.png"></a></td><td><a href="https://steemit.com/steemfest/@steemitboard/meet-the-steemians-contest-special-attendees-revealed">Meet the Steemians Contest - Special attendees revealed</a></td></tr><tr><td><a href="https://steemit.com/steemfest/@steemitboard/meet-the-steemians-contest-intermediate-results"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmeLukvNFRsa7RURqsFpiLGEZZD49MiU52JtWmjS5S2wtW/image.png"></a></td><td><a href="https://steemit.com/steemfest/@steemitboard/meet-the-steemians-contest-intermediate-results">Meet the Steemians Contest - Intermediate results</a></td></tr></table>

> You can upvote this notification to help all Steemit users. Learn why [here](https://steemit.com/steemitboard/@steemitboard/http-i-cubeupload-com-7ciqeo-png)!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-smjn-20181118t221505000z
categorydevelopment
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-11-18 22:15:03
last_update2018-11-18 22:15:03
depth1
children0
last_payout2018-11-25 22:15:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,618
author_reputation38,975,615,169,260
root_title"External modules without bundling in typescript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id75,519,997
net_rshares0
@steemitboard ·
Congratulations @smjn! You received a personal award!

<table><tr><td>https://steemitimages.com/70x70/http://steemitboard.com/@smjn/birthday1.png</td><td>1 Year on Steemit</td></tr></table>

<sub>_[Click here to view your Board of Honor](https://steemitboard.com/@smjn)_</sub>


> You can upvote this notification to help all Steemit users. Learn why [here](https://steemit.com/steemitboard/@steemitboard/http-i-cubeupload-com-7ciqeo-png)!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-smjn-20181214t125014000z
categorydevelopment
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-12-14 12:50:15
last_update2018-12-14 12:50:15
depth1
children0
last_payout2018-12-21 12:50:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length439
author_reputation38,975,615,169,260
root_title"External modules without bundling in typescript"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id76,829,764
net_rshares0