DEV Community

Cover image for Writing Single Page Application With Nim 👑
Ethosa
Ethosa

Posted on • Updated on

Writing Single Page Application With Nim 👑

Why Nim 🤔

Nim is powerful programming language that compiles into C, Cpp, ObjC and JS (what we need).

You can install it here

HappyX ✨

HappyX is an asynchronous web framework, written in Nim.
Source code
We'll work with it.

nimble install happyx
Enter fullscreen mode Exit fullscreen mode

Getting Started 👔

You should create project. Choose project name and mark project type as SPA.

hpx create
Enter fullscreen mode Exit fullscreen mode

You should move into project folder after this.

cd PROJECT_NAME
Enter fullscreen mode Exit fullscreen mode

Development 🛠

Let's launch project.

hpx dev --reload
Enter fullscreen mode Exit fullscreen mode

The dev command will hosts our project at localhost:5000.
Flag --reload will checks all changes in project.

Also you can use flags --host=0.0.0.0 and --port:1234 💡

Now you can change anything and see result in opened web page! 🙂

Let's change main.nim. For it you should open src/ folder and open main.nim file. You will see

import
  happyx,  # import main library
  components/[hello_world]  # import components

# Binds single page application to element with id "app"
# In our case - <div id="app"></div>
# Command `hpx create` reproduce all need files
appRoutes("app"):
  "/":  # Route our app
    component HelloWorld  # It is a component usage
Enter fullscreen mode Exit fullscreen mode

Try to change "/" route

"/":
  component HelloWorld
  tButton:  # tButton will reproduce <button> tag
    "Click me!"  # This will reproduce only text
    @click: # This will handle button clicks
      # Here you can use real Nim code 💡
      # As example you can write in browser console
      echo "Clicked!"
Enter fullscreen mode Exit fullscreen mode

OK, save it and see result! 🙂

Component Development 🛠

Move into src/components/ folder. Here automatically created component hello_world.nim

import happyx  # Import main library

# component declaration
component HelloWorld:
  `template`:  # HTML part 📕
    # Here you can write HTML
    "Hello, world!"

  `script`:  # Script part, optionally 🛠
    # Here you can use real Nim code 💡
    echo "Start coding!"

  # Also can be `style` part with component styles 🎴
  # `style`:
  #   """
  #   div {
  #     background: gray;
  #   }
  #   """
Enter fullscreen mode Exit fullscreen mode

That's all! Good Luck! 🙂

Also you can read about API in Nim

Top comments (1)

Collapse
 
horanchikk profile image
Morozov Vadim

🔥🔥🔥