使用 tsyringe 进行依赖注入,与 TypeScript 进行反应

Jor*_*nur 5 rest web typescript reactjs tsyringe

我目前的 React TypeScript 项目遇到了问题。

我用创建了我的项目npx create-react-app my-app --template typescript

我最近添加了 tsyringe 用于依赖注入,并尝试为 apiService 实现它。在按照自述文件(https://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection)添加原始值之后,我遇到了障碍。我已经将experimentalDecoratorsemitDecoratorMetadata添加到我的tsconfig.json文件中,但没有成功。

我遇到的错误实际错误是:

./src/ts/utils/NetworkService.ts 9:14
Module parse failed: Unexpected character '@' (9:14)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
| let NetworkService = (_dec = singleton(), _dec(_class = (_temp = class NetworkService {
>   constructor(@inject('SpecialString')
|   value) {
|     this.str = void 0;
Run Code Online (Sandbox Code Playgroud)

我相当确定这个问题是由 Babel 引起的,但是我使用 npm create react-app --template typescript 创建了这个问题,并且似乎无法访问 Babel 配置。

网络服务.ts

@singleton()
export default class NetworkService
{

    private str: string;
    constructor(@inject('SpecialString') value: string) {
        this.str = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

调用方法

bob() 
{
    const inst = container.resolve(NetworkService);
}
Run Code Online (Sandbox Code Playgroud)

在index.ts中注册类

container.register('SpecialString', {useValue: 'https://myme.test'});


@registry([
    { token: NetworkService, useClass: NetworkService },
])
class RegisterService{}

Run Code Online (Sandbox Code Playgroud)

Jor*_*nur 4

React-Scripts 管理许多与项目相关的配置。在很多情况下,这很好,而且实际上是一个很好的功能。然而,由于 React-Scripts 使用 Babel 作为其开发环境,并且不公开配置。

您必须运行 npm run eject才能公开配置。

请注意,这是一项单向操作且无法撤消。就我个人而言,我更喜欢对我的配置进行更多控制。

之后,您可以在新创建的config文件夹编辑webpack.config.js 。

开发环境中找到与babel-loader相关的部分,并将其添加plugins 数组中。 'babel-plugin-transform-typescript-metadata'