Write and run a LoopBack 4 "Hello World" project in TypeScript.

Prerequisites

Install Node.js (version 8.9 or higher) if itis not already installed on your machine.

Install LoopBack 4 CLI

The LoopBack 4 CLI is a command-line interface that scaffolds a project or anextension by generating the basic code. The CLI provides the fastest way to getstarted with a LoopBack 4 project that adheres to best practices.

Install the CLI globally by running

  1. npm i -g @loopback/cli

Create a new project

The CLI tool will scaffold the project, configure the TypeScript compiler, andinstall all the required dependencies. To create a new project, run the CLI asfollows and answer the prompts.

  1. lb4 app

Answer the prompts as follows:

  1. ? Project name: getting-started
  2. ? Project description: Getting started tutorial
  3. ? Project root directory: (getting-started)
  4. ? Application class name: StarterApplication
  5. ? Select features to enable in the project:
  6. ❯◉ Enable eslint: add a linter with pre-configured lint rules
  7. Enable prettier: install prettier to format code conforming to rules
  8. Enable mocha: install mocha to run tests
  9. Enable loopbackBuild: use @loopback/build helpers (e.g. lb-eslint)
  10. Enable vscode: add VSCode config files
  11. Enable docker: include Dockerfile and .dockerignore
  12. Enable repositories: include repository imports and RepositoryMixin
  13. Enable services: include service-proxy imports and ServiceMixin

Starting the project

The project comes with a “ping” route to test the project. Let’s try it out byrunning the project.

  1. cd getting-started
  2. npm start

In a browser, visit http://127.0.0.1:3000/ping.

Adding your own controller

Now that we have a basic project created, it’s time to add our owncontroller. Let’s add a simple “Hello World” controller asfollows:

  1. lb4 controller
  • Note: If your application is still running, press CTRL+C to stop itbefore calling the command

  • Answer the prompts as follows:

  1. ? Controller class name: hello
  2. ? What kind of controller would you like to generate? Empty Controller
  3. create src/controllers/hello.controller.ts
  4. update src/controllers/index.ts
  5. Controller hello was now created in src/controllers/
  • Paste the following contents into the file/src/controllers/hello.controller.ts:
  1. import {get} from '@loopback/rest';
  2. export class HelloController {
  3. @get('/hello')
  4. hello(): string {
  5. return 'Hello world!';
  6. }
  7. }

Code sample

You can view the generated code for this example at:hello-world