简体   繁体   English

如何将 redux-persist 添加到 typescript 项目?

[英]How to add redux-persist to typescript project?

I'm trying to add redux-persist to my React project (using typescript).我正在尝试将 redux-persist 添加到我的 React 项目中(使用打字稿)。 But I have some trouble.但我有一些麻烦。 Compiling falls with following error:编译出现以下错误:

Could not find a declaration file for module 'redux-persist/lib/storage'. '.../WebstormProjects/catalog/node_modules/redux-persist/lib/storage/index.js' implicitly has an 'any' type.
  Try `npm install @types/redux-persist` if it exists or add a new declaration (.d.ts) file containing `declare module 'redux-persist/lib/storage'

I installed the following packages: "@types/redux-persist": "^4.3.1" and "redux-persist": "^6.0.0".我安装了以下软件包:“@types/redux-persist”:“^4.3.1”和“redux-persist”:“^6.0.0”。

Content of redux-persist/lib/storage: redux-persist/lib/storage 的内容:

declare module "redux-persist/es/storage" {
  import { WebStorage } from "redux-persist/es/types";

  const localStorage: WebStorage;
  export default localStorage;
}

declare module "redux-persist/lib/storage" {
  export * from "redux-persist/es/storage";
  export { default } from "redux-persist/es/storage";
}

What to do to solve this problem?怎么做才能解决这个问题?

Solution:解决方案:

Add this line:添加这一行:

/// <reference types="redux-persist" />

to react-app-env.d.ts if your using create-react-app . react-app-env.d.ts如果您使用create-react-app

Explanatation:解释:

Triple-slash directives in typescript are single-line comments containing a single XML tag.打字稿中的三斜杠指令是包含单个 XML 标记的单行注释。 The contents of the comment are used as compiler directives .注释的内容用作编译器指令

These directives are utilised to declare a dependency on a package , which could be type, lib, path, etc..这些指令用于声明对包的依赖,包可以是类型、库、路径等。

The process of resolving these package names is similar to the process of resolving module names in an import statement.解析这些包名的过程类似于在 import 语句中解析模块名的过程。 An easy way to think of triple-slash-reference-types directives are as an import for declaration packages.三斜杠引用类型指令视为声明包的导入的一种简单方法。

For instance, in the code above, including /// <reference types="redux-persist" /> in a declaration file declares that this file uses names declared in @types/node/redux-persist.d.ts ;例如,在上面的代码中,在声明文件中包含/// <reference types="redux-persist" />声明该文件使用在@types/node/redux-persist.d.ts中声明的名称; and thus, this package needs to be included in the compilation along with the declaration file .因此,这个包需要与声明文件一起包含在编译中。

Read more here . 在这里阅读更多。

Solution:解决方案:

import storage of import storage from 'redux-persist/es/storage' and not import storage from 'redux-persist/lib/storage'从“redux-persist/es/storage”导入存储的导入存储,而不是从“redux-persist/lib/storage”导入存储

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM