Skip to content

Instantly share code, notes, and snippets.

@tbjgolden
Last active May 31, 2020 04:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tbjgolden/deb0d477de5d91a35d1b72a4fb24f537 to your computer and use it in GitHub Desktop.
How to use optionalDependencies in a Rollup library (with ES and TS examples)

Using csso as the example library I'm making an optional dependency

ES Module example (file.js)

let csso = globalThis && globalThis.csso
if (!csso) {
  import('csso')
    .then(_csso => {
      csso = _csso.default
    })
    .catch(() => {
      //
    })
}

TypeScript example (file.ts)

let csso: any = (globalThis as { csso?: any })?.csso
if (csso === undefined) {
  import('csso')
    .then(({ default: _csso }) => {
      csso = _csso
    })
    .catch(() => {
      //
    })
}

To use it

if (csso) {
  csso.minify(...)
} else {
  console.warn(
    '`csso` - an optional dependency - is not installed; CSS will not be minified'
  )
}

Make sure to add it to externals and output.globals (in all output formats)


If done right, you'll get something like these in each output format:

ES Module / IIFE / UMD
// iife and umd should be loaded globally as window.csso or global.csso
let csso = (_a = globalThis) === null || _a === void 0 ? void 0 : _a.csso;

// otherwise, esm will try and import it
if (csso === undefined) {
  import('csso').then(({
    default: _csso
  }) => {
    csso = _csso;
  }).catch(() => {//
  });
}
CJS (Node)
let csso = (_a = globalThis) === null || _a === void 0 ? void 0 : _a.csso;

if (csso === undefined) {
  Promise.resolve().then(function () { return _interopNamespace(require('csso')); }).then(({
    default: _csso
  }) => {
    csso = _csso;
  }).catch(() => {//
  });
}
@tbjgolden
Copy link
Author

tbjgolden commented May 31, 2020

(I'm almost certain there's a better or more elegant solution, but I wasn't able to find one when googling it)

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