DEV Community

loading...

Discussion on: ES-Next dynamic import

Collapse
aminnairi profile image
Amin • Edited

Let's say I have three modules.

$ touch {main,fibonacci,luhn}.mjs
// fibonacci.mjs
function fibonacci(number, oldFibonacci = 1) {
  if (number <= 1) {
    return oldFibonacci
  }

  return fibonacci(number - 1, oldFibonacci * number)
}

export default fibonacci
// luhn.mjs
function luhn(number) {
  return Array.from(number.toString()).reduce(function(sum, digit, index) {
    if (index % 2 === 0) {
      return sum + digit
    }

    const doubled = digit * 2

    if (doubled > 9) {
      return sum + (doubled - 9)
    }

    return sum + doubled
  }, 0) % 10 === 0
}

export default luhn

We could write an intermediary function that will return the default exported module out of a dynamic imported one.

// main.mjs
function importDefault(path) {
  return import(path).then(function(module) {
    return module.default
  })
}

Promise.all([
  importDefault("./fibonacci.mjs"),
  importDefault("./luhn.mjs")
]).then(function([ fibonacci, luhn ]) {
  console.log(fibonacci(5)) // 120
  console.log(luhn(732829320)) // true
  console.log(luhn(732829321)) // false
})

Of course, you can import named exported modules as well like usual.

// main.mjs
Promise.all([
  importDefault("./fibonacci.mjs"),
  importDefault("./luhn.mjs"),
  import("fs")
]).then(function([ fibonacci, luhn, { writeFile } ]) {
  console.log(fibonacci(5)) // 120
  console.log(luhn(732829320)) // true
  console.log(luhn(732829321)) // false

  writeFile("test.txt", "hello world!", function(error) {
    if (error) {
      console.error("test file error")
    } else {
      console.log("test file written")
    }
  })
})

N.B.: if you want to test this code, you'll have to run this command with a compliant version of Node.js supporting experimental modules.

$ node --experimental-modules ./main.mjs
Collapse
llldar profile image
Nathaniel Author

Nice complement, I didn't mention I was using esm. If anyone want to use the import export without having to name your file .mjs on node, try it out.