Skip to content

Instantly share code, notes, and snippets.

@dy
Last active May 31, 2018 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dy/d64175125ec45e4509d376c3eb170106 to your computer and use it in GitHub Desktop.
Save dy/d64175125ec45e4509d376c3eb170106 to your computer and use it in GitHub Desktop.
Browserify optional dependency

The problem: make require not to throw error when a package is not in installed.

A. browserify-optional

B. Dynamic require:

var react
try {
  var a = 'react'
  react = require(a) // Cannot find module 'react'
}
catch (e) {}

Once react is included by user, that automatically resolves:

// in userland
require('react')

// in package land
var a = 'react'
require(a) // ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment