Lead requirements

Install Node.js (version 8.9 or later) if it has not been installed before.

Install LoopBack 4 CLI

LoopBack 4 CLI is a command-line project scaffolding and an extension for generating basic code. The CLI provides a quick way to create LoopBack 4 projects, and it is a good practice to take this approach.

Run the following code from the command line to install the global CLI program.

npm i -g @loopback/cli
Copy the code

Create a new project

CLI tools scaffolding the project, configure the TypeScript compiler, and install any other required dependencies. Run the following CLI command to create a new project, and then enter the information as prompted:

lb4 app
Copy the code

Enter the following information as prompted: (In order: Project name, project description, project root directory, Application class name, enable function options)

? Project name: getting-started ? Project description: Getting started tutorial ? Project root directory: (getting-started) ? Application class name: StarterApplication ? Select features to enable in the project: ❯◉ enable eslint: Add a linter with pre-configured Lint rules ◉ Enable prettier: Install prettier to format code conforming to rules ◉ Enable mocha: Install Mocha to run tests ◉ Enable loopbackBuild: Use @loopback/build helpers (e.g. lb-eslint) ◉ Enable vscode: add vscode config files ◉ Enable docker: Include Dockerfile and.dockerignore ◉ Enable repositories: Include Repository imports and RepositoryMixin ◉ Enable Services: include service-proxy imports and ServiceMixinCopy the code

Start the project

The project has a “ping” route for testing purposes. Let’s try to get the project started:

cd getting-started
npm start
Copy the code

In the browser, visit http://127.0.0.1:3000/ping

Add your own controller

Now that we have a basic project, it’s time to add our own Controller. Let’s add a simple “Hello World” control class by running the following command:

lb4 controller
Copy the code
  • Note: If your project is still running, press before running the command CTRL+C To stop it.
  • Enter the following information as prompted: (In order: class name, automatically generated code template. Template control classes and control classes with CRUD are available.
? Controller class name: hello
? What kind of controller would you like to generate? Empty Controller
  create src/controllers/hello.controller.ts
  update src/controllers/index.ts

Controller hello was now created in src/controllers/
Copy the code
  • Copy and paste the following content to the file/SRC/controllers/hello.html controller. Ts:
import { get } from "@loopback/rest";

export class HelloController {
  @get("/hello")
  hello(): string {
    return "Hello world!";
  }
}
Copy the code
  • Start the project with the NPM start command.
  • In the browser, visit http://127.0.0.1:3000/hello, you can see the text Hello world!

References:

  • The loopback. IO/doc/en/lb4 /…