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

Allow dynamic import in UMD builds #3491

Open
johannes-z opened this issue Apr 9, 2020 · 2 comments
Open

Allow dynamic import in UMD builds #3491

johannes-z opened this issue Apr 9, 2020 · 2 comments

Comments

@johannes-z
Copy link
Contributor

Feature Use Case

Dynamic imports should work in UMD environments as well:

async function test () {
  const mod = await import('some-external-lib')
  console.log(mod)
}
test()

AMD and I think CommonJS also are transformed correctly, e.g. AMD compiles to:

return new Promise(function (resolve, reject) { require(['some-external-lib'], function (m) { resolve(_interopNamespace(m)); }, reject) });

Feature Proposal

In UMD builds the dynamic import should be replaced by a UMD factory. I wrote a plugin to do this for me for now, but I think something like this should be builtin:

/**
 * Replaces named, dynamic imports with an UMD factory. Absolute and relative imports are ignored.
 *
 * Requires an environment that supports `Promise`.
 */
function pluginDynamicImports (options = {}) {
  return {
    name: 'dynamic-imports',
    transform(code, filename) {

      // TODO: warn/error if globalName is not specified in UMD environment.
      // TODO: global is hardcoded to window, which is wrong.
      const transformedCode = code.replace(/import\(['"`](?![\.\/])(.*?)['"`]\)/gi, (match, request) => {
        const globalName = options.globals[request]
        return `new Promise(function (resolve, reject) {
          (function (global) {
            typeof exports === 'object' && typeof module !== 'undefined' ? resolve(require("${request}")) :
            typeof define === 'function' && define.amd ? require(["${request}"], resolve, reject) :
            (global = global || self, resolve(global["${globalName}"]));
          }(window));
        })`
      })

      return transformedCode
    },
  }
}
@dutchigor
Copy link

This is axactly what I'm looking for! @johannes-z , can you point me to / provide me with the plugin that you created?

@johannes-z
Copy link
Contributor Author

johannes-z commented Jul 8, 2021

@dutchigor I haven't used this in months, but the code I posted above is the plugin: function pluginDynamicImports .... You should be able to add it to your rollup.config.js like so:

{
  ...
  plugins: [
    pluginDynamicImports({
      globals: { // optional
        'some-lib': 'SomeLib' // loads 'some-lib' from window.SomeLib
      }
    })
  ]
  ...
}

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

2 participants