3.4 Loading packages conditionally

The :if, :when, and :unless keywords predicates the loading and initialization of packages. They all accept one argument, an Emacs Lisp form that is evaluated at run-time.

If the argument of the :if keyword evaluates to non-nil, the package will be loaded and initialized. The :when keyword is provided as an alias for :if. Finally, the :unless keyword is the inverse of :if, such that :unless foo means the same thing as :if (not foo).

For example, if you only want to load ‘foo’ in graphical Emacs sessions, you could use the following:

(use-package foo
  :if (display-graphic-p))

Some common use cases

Here are some common cases for conditional loading, and how to achieve them.

Making conditional loading affect :preface and :ensure

If you need to make a use-package form conditional so that the condition occurs before even :ensure (see Installing package) or :preface (see :preface is evaluated first), use when around the use-package form itself. For example:

(when (memq window-system '(mac ns))
  (use-package foo
    :ensure t))