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:
- Find a way to set up
tsconfigto treat each file as separated file. I haven't found a good solution to this - In
.tsfile, declare the global variable inside the IIFE. But I ran into errorModifiers cannot appear here.
Any helps are appreciated. Thanks!
<script type="module" src="xxx.js"></script>but like you said it is the php that does the include of the file