Global imports

In C#, when we write using System; in many files, we can reduce its repetition by writing it as global using System; in one file, and then all files have it.

I see myself constantly writing import { camelize } from "base" and many more imports.
It would be a great help not to repeat it repeatedly.

The main reason for this is refactoring. When the name of the imported module changes, or the barrel name changes, we should reflect those changes in many places.

Using global imports, we can reduce that refactoring cost, make our codes one step cleaner, and reduce the boilerplate.

And AMAIK, this won't cause problems in tree-shaking, because that module is already imported once and would be part of the final tree.

The proposed syntax is:

global import { camelize } from "base"

This means that all files will get this import.

That would erase the entire benefit of modules - explicitness. That you have to write imports repeatedly is a good thing - code is written a few times and read many many times, so always optimize for reading, not for writing.

Import Maps or package.json aliases help, they provide a layer of indirection so a rename only has to be updated in one place

1 Like

JS has global variables already. They're a bit cumbersome to create in module code, but that is on purpose - they are usually not a good idea. In your case, that would be

import { camelize } from "base";
globalThis.camelize = camelize;

Or maybe you even want

import * as base from "base";
Object.assign(globalThis, base);
// or
Object.assign(globalThis, await import("base"));
2 Likes