Tree Nguyen
Tree Nguyen

Reputation: 1199

Handling global variable locally in a file in Typescript

my company's working way is quite weird. We use a PHP template engine to copy all of file into a single HTML and serve it. It goes as follow:

Main html

<script>
    (() => {
        const foo = 'bar';
        {{ include('xxx.js') }}
    })
    {{ include('zzz.js') }}
</script>

xxx.ts

declare const foo: string;
(() => {
    console.log(foo);
})()

As you can see, there are 2 layers of IIFE, one in the main HTML and another one in each .ts to ensure the scope of variable is contained correctly in each .ts file. I then compile xxx.ts into xxx.js using tsc.

The problem is that now I have an additional file yyy.ts that I want to include right below xxx.ts in the main.html's IIFE. Lets assume yyy.ts is exactly the same with xxx.ts.

yyy.ts

declare const foo: string;
(() => {
    console.log(foo);
})()

Here I run into an issue at foo in both file. The error is Cannot redeclare block-scoped variable.

I can't put the foo into a global.d.ts file cause it's not global since it's only valid to xxx.js and yyy.js

I have done some reading and see that the way TS compile is that if the file doesn't have import/export, it will treat all of the variable as global variable.

How can I solve this issue? 2 ways that I can kind of think of are:

Any helps are appreciated. Thanks!

Upvotes: 0

Views: 1341

Answers (1)

Keith
Keith

Reputation: 24181

I've a feeling you didn't understand my point about the IIFE been done in PHP and not TS. So I thought it might make sense if I show some example.

From what I can gather say you have a global var called foo, and you want that to be included in xxx & zzz..

First, don't put the IIFE inside the TS files. Otherwise like you have found out your going to get Cannot redeclare block-scoped variable

So below is an idea that I believe will do what your after.

File xxx.TS

declare const foo: string;

const msg = "hello";
console.log(`${msg) ${foo)`);

File zzz.TS

declare const foo: string;

const msg = "goodbye";
console.log(`${msg) ${foo)`);

Now if inside our PHP file we did ->

<script>
    (() => {
      const foo = 'bar';
      (() => { {{ include('xxx.js') }} })
      (() => { {{ include('yyy.js') }} })
    })
</script>

So in the above, firstly you have a global var foo, but only global for your TS files, each TS files can also have it's own local vars. In above you can see I've defined a local var msg that has hello & goodbye different in each TS file.

So if you run the above you should then see something like ->

hello bar
goodbye bar

And none of the above is going to pollute your windows global.

Upvotes: 1

Related Questions