Search code examples
javascriptnode.jsamdrollupjssvelte

Using Rollup + Svelte with third party AMD libraries


I understand that Svelte can produce AMD output and find some details on how to do this in the docs. I can also find some info on how to configure Rollup to output AMD modules. But what about input? What do I need to do when I have AMD modules as dependencies?

For example, suppose I have two different third party libraries that are both distributed as AMD libraries and I want to use those libraries in my Svelte project. How would I need to modify eg. this nested components demo to allow these AMD modules to be used as dependencies in my Svelte components?

Also, am I able to configure whether I bundle these libraries together with my Svelte components? If so, where would I need to do that?


Note

I also raised this issue on Github.


Solution

  • AMD modules are a pain to convert to ES modules, so you may find it difficult to bundle them with Rollup. (There's rollup-plugin-amd but it comes with caveats.)

    But you can easily treat them as external dependencies that get loaded separately — just import them as normal then configure Rollup:

    // rollup.config.js
    export default {
      // ...
      format: 'amd',
      external: ['an-external-amd-module'],
      paths: {
        'an-external-amd-module': 'https://my-cdn.com/an-external-amd-module.js'
      }
    };
    

    You can see a demo here (repo here) — note that we're loading an exernal AMD module called the-answer, even though it's a regular import, because of the Rollup config.