Automatic Loading of Packages

Other tutorials have discussed explicit loading of Wolfram Language packages using <<package and Needs[package]. Sometimes, however, you may want to set the Wolfram Language up so that it automatically loads a particular package when the package is needed.

You can use DeclarePackage to give the names of symbols which are defined in a particular package. Then, when one of these symbols is actually used, the Wolfram Language will automatically load the package where the symbol is defined.

declare that a package should automatically be loaded if a symbol with any of the names namei is used

Arranging for automatic loading of packages.

This specifies that the symbols VariationalD, EulerEquations, and FirstIntegral are defined in VariationalMethods`:
Click for copyable input
When you first use VariationalD, the Wolfram Language automatically loads the package that defines it:
Click for copyable input

When you set up a large collection of Wolfram Language packages, it is often a good idea to create an additional names file which contains a sequence of DeclarePackage commands, specifying packages to load when particular names are used. Within a particular Wolfram System session, you then need to load explicitly only the names file. When you have done this, all the other packages will automatically be loaded if and when they are needed.

DeclarePackage works by immediately creating symbols with the names you specify, but giving each of these symbols the special attribute Stub. Whenever the Wolfram Language finds a symbol with the Stub attribute, it automatically loads the package corresponding to the context of the symbol, in an attempt to find the definition of the symbol.