How to Create Package in Julia?

How to Create Package in Julia?

  • Julia
  • 2 mins read

To create a package in Julia, you can use the Pkg.generate function from the Pkg module. This function takes the name of the package and the path where it should be created as arguments and generates the necessary files and directories for the package. For example, to create a package called "MyPackage" in the current working directory, you could use the following code:

This will create the following files and directories in the current working directory:

using Pkg

# Generate the package files and directories
# Enter the Pkg REPL-mode
]
generate MyPackage

The src/ directory is where you will put the source code for your package, the test/ directory is where you will put the test cases for your package, and the Project.toml and Manifest.toml files are used to manage the dependencies and metadata for your package.

MyPackage/
├── src/
├── test/
├── Project.toml
└── Manifest.toml

Once you have generated the package files and directories, you can start writing the source code for your package. For example, to add a function called hello that prints "Hello, world!" to the MyPackage package, you could create a file called hello.jl in the src/ directory with the following code:

# src/hello.jl

function hello()
    println("Hello, world!")
end

To use this function in your code, you will need to activate the MyPackage package using the Pkg.activate function, and then import the hello function using the using keyword. For example:

using Pkg

# Activate the MyPackage package
# Enter the Pkg REPL-mode
]
activate MyPackage

# Import the hello function
# exit the package prompt
Julia> using MyPackage

# Use the hello function
hello()

Here is the output of this code:

Hello, world!

These are just a few examples of how to create and use a package in Julia. For more information, I would recommend checking out the documentation for the Pkg module.

Related:

  1. How to Check if Package is Installed in Julia?