Issue
Imagine a library with an unlimited number of functions, each residing in its own file:
- doSomethingAlpha.ts
- doSomethingBravo.ts
- doSomethingCharlie.ts
- ...
Some functions reference the global variable __LANGUAGE_CODE__
:
export default function doSomethingAlpha(): void {
if (__LANGUAGE_CODE__ === "en") {
console.log("English");
} else if (__LANGUAGE_CODE__ === "ja") {
console.log("日本語");
}
// ...
}
The __LANGUAGE_CODE__
:
- Should not rely on the environment (functions may be used in either a browser or Node.js, but must first be compiled to JavaScript and bundled into the user's project). This rules out using
window
. - Comes with a default value that can be changed by anyone using the library:
export { doSomethingAlpha } from "library";
doSomethingAlpha(); // "English"
__LANGUAGE_CODE__ = "ja";
doSomethingAlpha(); // "日本語"
Additionally:
- The library is distributed without being pre-compiled to JavaScript (so no Webpack DEFINE plugin usage). Users of the library can bundle it to their projects using Webpack (or just TypeScript compiler), but the library itself is unaware of Webpack.
- The library lacks a centralized entry point: users only take the specific function they need.
Innovative Solution Considerations
We could inform TypeScript about __LANGUAGE_CODE__
within the library by creating a **.d.ts
file and declaring:
declare const __LANGUAGE_CODE__: string;
An unresolved issue remains regarding how to set the default value.
export { doSomethingAlpha } from "library";
doSomethingAlpha(); // no output because "__LANGUAGE_CODE__" is undefined