Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Last active May 31, 2019 14:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rich-Harris/9ee5338527e7fa4ab251a02685729ee7 to your computer and use it in GitHub Desktop.
Save Rich-Harris/9ee5338527e7fa4ab251a02685729ee7 to your computer and use it in GitHub Desktop.
rollup-plugin-unpkg behaviour

From this Twitter convo. It would be cool to have a plugin that allowed you to use bare module specifiers (import * as React from 'react') in your app, and converted them to unpkg.com URLs.

Say you have these two source files:

// main.js
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import message from './message.js';

class App extends React.Component {
  render() {
    return (
      <h1>{message}</h1>
    );
  }
}

ReactDOM.render(<App/>, document.body)
// message.js
export default 'Hello world!';

Rollup (or webpack, if you're into that sort of thing) could generate this output, determining from the relevant package.json files that a) react and react-dom have the module field (note: they currently don't), and b) we're using a specific version of each:

import * as React from 'https://unpkg.com/react@16.1.1/esm/index.js?module';
import * as ReactDOM from 'https://unpkg.com/react-dom@16.1.1/esm/index.js?module';

const message = 'Hello world!';

class App extends React.Component {
  render() {
    return (
      <h1>{message}</h1>
    );
  }
}

ReactDOM.render(<App/>, document.body)

Stick a <script type='module' src='bundle.js'></script> in your index.html and you're off to the races.

@ansballard
Copy link

Sorry for the necromancy, but I was looking around for an existing solution to this and couldn't find any. I went as far as transforming a given list of modules to their unpkg url counterpart, passing the version from package.json if it exists. But I can't find a way to return a url from the resolveId hook, or any obvious (to me at least) ways to allow for returning "invalid" import paths via plugin. Is there a built in way to handle importing URLs and the like, or at least not trying to resolve them after resolveId()? Otherwise this idea really requires base changes to rollup itself, and from there the plugin to handle routing to unpkg is pretty straightforward.

@osdevisnot
Copy link

I gave this a shot here https://github.com/osdevisnot/rollup-plugin-unpkg

Still trying to wrap up the documentation and tests, but one should be able to consume it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment