【问题标题】:Can't resolve 'crypto-js' in React Typescript无法解析 React Typescript 中的“crypto-js”
【发布时间】:2019-11-20 16:15:59
【问题描述】:

我尝试使用 crypto-js 在 react typescript run with docker compose 中使用,但出现以下错误

找不到模块:无法解析“/app/crypto”中的“crypto-js”

这是我导入的crypto-js。例如:

import crypto from 'crypto-js';

export const encrypt = (key: string, evalue: any) => {
    const secret_key = crypto.SHA256(key);
    return crypto.AES.encrypt(evalue, secret_key).toString();
};

我试了很多次,还是不行。

【问题讨论】:

  • 你能给我们看看你的tsconfig文件吗?另外,您是否已经在项目中使用了其他 node_modules?
  • 是的,这是我的 tsconfig 文件:``` { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext " ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution" :“节点”,“resolveJsonModule”:真,“isolatedModules”:真,“noEmit”:真,“jsx”:“反应”},“包括”:[“src”]}```

标签: reactjs typescript encryption docker-compose cryptojs


【解决方案1】:

我最好的猜测是 Typescript 需要一些包的类型定义。

尝试运行npm install @types/crypto-js --save-dev

【讨论】:

  • 嗯...您可以尝试停止开发服务器,删除 node_modules 并重新安装
  • 您的 docker 镜像是否映射到本地环境中的卷?如果不是这种情况,可能是您的 node_modules 没有安装:)
  • 用 docker 管理 node_modules 包老实说对我来说总是很痛苦
【解决方案2】:

关于您的tsconfig.json 文件,我相信这是因为您指定了"include": [ "src" ],所以这意味着所有node_modules 都将被跳过。 尝试删除它并改用baseUrl 选项。

构建项目不需要这些类型(除非您使用strict 标志)。但正如@Kael 所说,安装它们可能很有用。所以你可以指定

"typeRoots": [
  "node_modules/@types"
],

在你的配置文件中

【讨论】:

  • 它对我不起作用。我仍然遇到同样的错误:Failed to compile ./src/components/crypto/crypto.ts Module not found: Can't resolve 'crypto-js' in '/app/src/components/crypto'
【解决方案3】:

尝试在你的 types.d.ts 中声明

declare module 'crpyto-js' {
}

如果这可行,我们现在至少您的 TypeScript 设置应该是正确的。

然后你只需要安装@types/crypto-js 包并再次删除你的模块声明。 如果这不起作用,您的 typescript 配置不是您的 node_modules/@types 文件夹。

然后在你的 tsconfig.json 中设置你的 TypeRoots

  "compilerOptions": {
       "typeRoots" : ["./typings", "node_modules/@types"]
   }
}

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 2022-11-04
    • 1970-01-01
    • 2020-04-29
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多