tc39 / proposal-module-expressions

https://tc39.es/proposal-module-expressions/
MIT License
438 stars 18 forks source link

Add an example of bundled modules referencing each other #53

Open jurca opened 3 years ago

jurca commented 3 years ago

Loving the proposal so far, however, I disagree that this cannot be useful for bundling, despite all modules defined as module blocks being anonymous and unable to directly reference each other.

Please consider the following pattern:

// Define modules relying on each other
const module1 = module {
  export function add(a, b) {
    return a + b
  }
}

const module2 = module {
  const imported = {
    // Prevent too eager consumption of imported values
    get add() { throw new Error('"add" has not been imported yet') },
  }

  export function setImports(importedValues) {
    Object.defineProperties(imported, importedValues)
  }

  export function sum(...numbers) {
    return numbers.reduce((sum, value) => imported.add(sum, value), 0)
  }
}

// Initialize modules
const [module1Exports, module2Exports] = await Promise.all([import(module1), import(module2)])

// Link modules
module2Exports.setImports({add: {get() { return module1Exports.add }}})

// Use linked modules
assert(module2Exports.sum(1, 2, 3, 4, 5) === 15)

Admissibly, this pattern would require the bundler to move any import-dependent top-level business logic to an exported function (let's call it init), which would be invoked during the linking stage once the init function's dependencies have been provided. Not necessarily all imports of the module need to be provided at that point, the rest can wait for the init function to complete and possibly update the exported values. (Or just flatten the bundle to work around this.)

This pattern allows for lazily referenced circular dependencies as well.

Thus I do not think that using JavaScript Module Fragments would be required, although those would do the linking stage for you and thus be a lot easier to use than hand-writing this.