       @logger.verbose "unloading: #{ id }"
       delete require.cache[id]
 
+    @setupLocals()
+
   setConfig: (@config) ->
     @contentsPath = @resolvePath @config.contents
     @templatesPath = @resolvePath @config.templates
+
+  setupLocals: ->
+    ### Resolve locals and loads any required modules. ###
+    @locals = {}
+
+    # Load locals json if neccessary
+    if typeof @config.locals == 'string'
+      filename = @resolvePath @config.locals
+      @logger.verbose "loading locals from: #{ filename }"
+      @locals = readJSONSync filename
+    else
+      @locals = @config.locals
+
+    # Load and add modules specefied with the require option to the locals context.
+    for alias, id of @config.require
+      logger.verbose "loading module '#{ id }' available in locals as '#{ alias }'"
+      if @locals[alias]?
+        logger.warn "module '#{ id }' overwrites previous local with the same key ('#{ alias }')"
+      @locals[alias] = @loadModule id
+
+    return
 
   resolvePath: (pathname) ->
     ### Resolve *pathname* in working directory, returns an absolute path. ###

    loadTemplates this, callback

  getLocals: (callback) ->
    ### Resolve locals. ###

    resolveLocals = (callback) =>
      ### Load locals json if neccessary. ###
      if typeof @config.locals == 'string'
        filename = @resolvePath @config.locals
        @logger.verbose "loading locals from: #{ filename }"
        readJSON filename, callback
      else
        callback null, @config.locals

    addModules = (locals, callback) =>
      ### Loads and adds modules specefied with the require option to the locals context. ###
      async.forEach Object.keys(@config.require), (alias, callback) =>
        module = @config.require[alias]
        logger.verbose "loading module '#{ module }' available in locals as '#{ alias }'"
        @loadModule module, (error, result) ->
          if not error?
            if locals[alias]?
              logger.warn "module '#{ module }' overwrites previous local with the same key ('#{ alias }')"
            locals[alias] = result
          else
            error.message = "Error loading module '#{ module }': #{ error.message }"
          callback error
      , (error) -> callback error, locals

    async.waterfall [
      resolveLocals
      addModules
    ], callback

  load: (callback) ->
    ### Convenience method to load plugins, views, contents, templates and locals. ###

{render} = require './renderer'
{runGenerator} = require './generator'

{readJSON, readJSONSync} = utils

class Environment
  ### The Wintersmith environment. ###
