Shortened Import Statement

In the current ECMAScript Specifications, Imports look something like this

import { Module } from "/Module.mjs";

I am not asking for a replacement for this, in fact ECMAScript's import system is one of the best ones. But many modules only have one import. Some examples of this include

import { Module } from "/Module1.mjs";
import DefaultModule from "/Module2.mjs";
import { ModuleTres as Module3 } from "/Module3.mjs";

My Solution is an import statement like Python or Java, like this

import "/Module1.mjs";
import "/Module2.mjs" as Mod2;
import "/Module2.mjs" as globalThis;

It would automatically create an object with the same name as the file name, but with some rules:

  1. Dashes are replaced with Underscores
  2. Spaces are replaced with Underscores
  3. Any JS Reserved word will cause an error if by itself
  4. Invalid Characters will cause an error

Using as will let you be able to choose what the import is called. To create a single export file, use export only instead of export or export default. For example:

export only {
   property: 0,
   method: (x) => x * 2 + 1
}
1 Like

Modules with one export are already importable with import DefaultModule from "/Module2.mjs";- you get to pick your own identifier ("DefaultModule"), and since the filename isn't part of the spec (the web has URLs, node has URLs-that-are-really-file-paths, for example).

Separately, import "/Module1.mjs"; is already legal syntax - conventionally, that indicates you're importing the module for side effects.

In other words, conceptually, a default export is what a module is, and a named export is something a module has. My personal opinion is that most modules should be something. So a module that only exports one thing IS that thing, and thus it's a default export.

2 Likes