unional unional - 2 months ago 22
Javascript Question

Detecting `import * as name` token

I'm writing some code that I want to apply only to the token from

import * as name from 'module-name'

Is there a way to do that? I recall there is a
flag or something similar but that is not in the official spec, so I'm not sure if that is the right approach (and I can't find the exact article talking about it, a reference would be of great help).

i.e. this is what I want (using TypeScript in the example):

import * as someModule from 'module-name'
import someDefault from 'module-name'
import { someNamed } from 'module-name'
import otherImport = require('cjs-module')

let somethingElse = {} // anything
checkIsStarModule(someModule) // true
checkIsStarModule(someDefault) // false
checkIsStarModule(someNamed) // false
checkIsStarModule(otherImport) // false
checkIsStarModule(somethingElse) // false

And what's the proper name to describe
import * as name ...
syntax? :)

EDIT: adding some context to the question.

I'm doing something similar to

And I want to apply it only to
as described above. This is because I don't want to accidentally execute
method on something that is not a module.

My API is
get(key: Newable<T> | T): Promise<T>
and I do allow consumers to throw in anything as
is simply any class).

Thanks @estus on
, and I realize that it is only for interop thus not useful in this context.


There is nothing that really distinguishes module namespace objects from others, anyone could create an object like that. You can test for

function isModuleNamespaceLike(o) {
    return o === Object(o)
    && o[Symbol.toStringTag] === "Module"
    && Object.getPrototypeOf(o) === null
    && !Object.isExtensible(o)
    && Object.getOwnPropertyNames(o).every(function(p) {
        var d = Object.getOwnPropertyDescriptor(o, p);
        return d.enumerable && !d.configurable;

or try to look for __esModule, but that depends on your transpiler.