rollup / rollup-starter-lib

Bare-bones example of how to create a library using Rollup

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to build for <script type="module">

oskarrough opened this issue · comments

commented

Hi, if your library depends on an external package, how can you build for <script type="module">? Bonus points if you can make it work as CJS, too.

Here's our library

// my-library.js
import fetch from 'isomorphic-unfetch'
export default function (url) {
  // do stuff
  return fetch(url)
}

Using rollup es format, can this work?

<script type="module">
  import myLibrary from './dist/my-library.es.js'
  myLibrary(42)
</script>

Right now you it warns you

Uncaught TypeError: Failed to resolve module specifier "isomorphic-unfetch". Relative references must start with either "/", "./", or "../".`

If you change the library's import to something like ./node_modules/isomorphic-unfetch/es-version.js it'll work locally but of course break the built version. What to do? What is this rabbit hole?

Any help would be great appreciated! Thank you.

Possibly related

Hey 🙂 I'm kinda new to rollup but also ran into this problem. The way I got around it is to use @rollup/plugin-node-resolve as a plugin when bundling modules for use in the browser, so that dependancies are all bundled up and no resolving is needed client-side. Something like:

// rollup.config.js
{
      input: 'src/main.js',
      output: {
          file: pkg.module,
          format: 'esm'
      },
      plugins: [
          resolve(),
      ]
},

Whereas if I was building out an es module to be used in Webpack / whatever I wouldn't bundle the dependancies and let the build tool handle it.

There might be a better way of handling this so if anyone has a better option give me a shout :)

Cheers!

@oskarrough it's not possible right now to change where the identifier points to.
In the future, we could probably use import-maps.

For me, it was a matter of changing:
from:

<script src="js/bootstrap.js" type="module"></script>

to:

<script type="module" src="js/bootstrap.js"></script>