Can I import npm packages dynamically from CDNs in Webpack?

Viewed 289

I need to require a different version of Zoid npm package dynamically in my JS bundle, depending on a variable. So for example:

if (isLatestVersion) {
  zoid = await import('https://unpkg.com/zoid@9.0.80/index.js')
} else {
  zoid = await import('https://unpkg.com/zoid@9.0.31/index.js')
}

However when I try the above I get this error:

script.js:2 Uncaught (in promise) Error: Cannot find module 'https://unpkg.com/zoid@9.0.80/index.js'
    at webpackMissingModule (script.js:2)

Presumably this is because I don't have zoid defined in my package.json.

So basically my question is, is there's a way to import libraries from a CDN such as unpkg.com or skypack.dev, using Webpack's dynamic imports (aka code splitting)?

1 Answers

The way I ended up solving this was by adding two versions of the same package in my package.json. So I ran these commands:

yarn add zoid9080@npm:zoid@9.0.80
yarn add zoid9031@npm:zoid@9.0.31
yarn remove zoid

Then I imported these two packages statically, since I didn't actually need dynamic importing, and the code ended up being simpler as well:

import zoid from 'zoid9080';
Related