Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an example of bundled modules referencing each other #53

Open
jurca opened this issue May 4, 2021 · 0 comments
Open

Add an example of bundled modules referencing each other #53

jurca opened this issue May 4, 2021 · 0 comments

Comments

@jurca
Copy link

jurca commented May 4, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant