javascriptnode.jsesmodules

Why are namespaced import entries sorted alphabetically?


In NodeJS:

// module.js
export const b = 1
export const a = 2

// index.js
import * as ns from './module.js'
console.log(Object.keys(ns)) // [a, b]

I cannot find why it is not the same as the export order, from reading the spec.


Solution

  • The spec for Module Namespace Exotic Objects says

    [[Exports]]: A List whose elements are the String values of the exported names exposed as own properties of this object. The list is sorted according to lexicographic code unit order.

    This list is used by [[OwnPropertyKeys]](), which Object.keys relies upon.

    The sorting explicitly happens in step 6 of ModuleNamespaceCreate (since ES7).