GuidesSetup Dev Environment

Setting up the development environment

TypeScript

Since redi’s API uses TypeScript decorator syntax, you need to enable experimentalDecorators in your tsconfig.json.

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}
đź’ˇ

Note: Make sure that TypeScript is translating your source code, not Babel, as Babel’s support for decorators is different from TypeScript. Please check the document of @babel/plugin-proposal-decorators and enable legacy option in your settings. Or you can use redi without decorators.

Scaffold Tool

Configuring your own development tools can be quite cumbersome. To get started quickly and enjoy the benefits of dependency injection, we have prepared a scaffold tool called redi-starter.

It provides the following features:

  • Integration of redi with proper TypeScript configuration
  • Integration with Prettier / ESLint / webpack / Jest
  • Support for loading different code based on the target platform, for example, not loading PcPlatformService code on mobile devices

Usage

Simply clone this project to your local machine:

git clone https://github.com/wzhudev/redi-starter.git

If you don’t want to keep the Git history, you can use the degit tool:

npx degit https://github.com/wzhudev/redi-starter

VSCode Snippets

The following snippets can make it easier to declare class dependencies:

{
  "Redi Injection Identifier": {
    "prefix": ["@I"],
    "body": [
      "@I${1:identifier} private readonly _${2:name}: I${1:identifier},"
    ],
    "description": "Inject an identifier with Redi."
  },
  "Redi Injection": {
    "prefix": ["@In"],
    "body": [
      "@Inject(${1:identifier}) private readonly _${2:name}: ${1:identifier},"
    ],
    "description": "Inject a class item with Redi."
  }
}

Using redi without decorators

Even if you are not using TypeScript, you can still use redi.

redi’s syntax dependency in TypeScript is limited to decorators, which are only used to declare dependencies on classes. JavaScript does not have decorators, so instead you can use setDependencies:

In TypeScript, you would have code like this:

class MapService {
  constructor(
    @SkipSelf()
    @ISatelliteService
    private readonly satellite: ISatelliteService,
  ) {}
}

The equivalent code in JavaScript would be:

class MapService {
  constructor(satellite) {
    this.satellite = satellite;
  }
}
 
setDependencies(MapService, [[new SkipSelf(), ISatelliteService]]);

As you can see, the syntax for declaring dependencies is consistent with declaring dependencies on factory functions.