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

React with TypeScript using tsyringe for dependency injection

我目前在使用 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;

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

NetworkService.ts

@singleton()
export default class NetworkService
{

    private str: string;
    constructor(@inject('SpecialString') value: string) {
        this.str = value;
    }
}

调用方式

bob() 
{
    const inst = container.resolve(NetworkService);
}

在index.ts

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


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

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

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

Please note, this is a one-way operation and can not be undone. Personally, I prefer more control with my configuration.

之后你可以编辑新创建的config中的webpack.config.js ]文件夹。

dev-environment中找到babel-loader相关的部分 'babel-plugin-transform-typescript-metadata'添加到插件数组

您可以使用“覆盖”某些参数的库来代替弹出。

我用过 craco : https://www.npmjs.com/package/@craco/craco