Your First Module

Your First Module

The one idea that makes modules work

Neovim automatically looks inside the lua/ folder of your config directory. When you write:

require("myconfig")

Neovim walks into lua/, finds myconfig/init.lua (or myconfig.lua), and runs it. Dots become folders: require("config.options") loads lua/config/options.lua. That is the entire trick.

Try it

~/.config/nvim/
├── init.lua
└── lua/
    └── myconfig/
        └── init.lua

lua/myconfig/init.lua:

-- myconfig module
print("myconfig loaded")

Add require("myconfig") to the bottom of init.lua, restart, and the message appears. Delete the print once the point is made.

Why bother

A single init.lua works at twenty lines and hurts at two hundred. Modules give every concern a small home — options, keymaps, plugins — which is exactly how the modern config chapter structures a real configuration.

require runs a module once and caches it; a second require of the same name returns the cached result rather than re-running the file. Keep modules as definitions, not actions, and this only ever helps.