Crystal Notes: Importing Code
Published: 2021-08-16
Intro
In Crystal, code is imported with the require statement.
crystal
# Import stuff.cr from the current directory.
# OR import stuff.cr from the ./stuff/ directory if it exists.
require "./stuff"
# Explicitly import the stuff.cr file from the
# current directory.
require "./stuff.cr"
# Import from parent directory.
require "../stuff"
# Import from N parent level directories.
require "../../stuff"
# Import from a subdirectory.
require "./stuff/things"
# Import all .cr files in the current directory.
require "./stuff/*"
# Import all .cr files in the current and sub directories.
require "./stuff/**"
# Import stuff.cr or stuff/stuff.cr from the standard library.
# OR import stuff.cr or stuff/stuff.cr from the ./lib directory.
require "stuff"
Considerations
- The compiler combines all required files together.
- A file can be required more than once, but only the first require statement has any effect.
- The standard library on Linux is located in the /opt/crystal/src/ directory.