Creating Your First Ballerina Package

The single source file program is a quick and easy way to get started with Ballerina. However, when your code grows, you need to create a Ballerina package to organize your code.

The below are the basic steps you need to know about writing a Ballerina package. It also introduces the package-related commands in the Ballerina command-line tool.

Creating the Package

To create a new Ballerina package, use the bal new command below.

bal new hello_world

This will create a new Ballerina package with a main function. If you are creating a service instead of a main function, pass the -t service option.

The bal new command generates the below.

cd hello_world
tree .
.
├── Ballerina.toml
└── main.bal
    
0 directories, 2 files

The sections below walk you through each of these files.

Ballerina.toml

The Ballerina.toml file identifies a directory as a Ballerina package.

.gitignore

The bal new command also generates the .gitignore file by default with target added as an entry.

main.bal

This file generated by the bal new command will contain code for a hello world application as shown below.

import ballerina/io;  

public function main() { 
    io:println("Hello World!"); 
}

Building the Package

Build the package and generate an executable JAR file as follows.

bal build
Compiling source
 	examples/hello_world:0.1.0 

Generating executable
    target/bin/hello_world.jar

Running the Package

Then, run it as follows.

bal run target/bin/hello_world.jar
Hello World!

Info: You can also use bal run to compile and then run it in a single step as follows.

bal run
Compiling source
    examples/hello_world:0.1.0

Running executable

Hello World!