styled-components的「无法找到命名空间 ‘NodeJS’。」

我觉得在使用React进行样式调整时,使用styled-components的人数似乎正在增加。
当我尝试在TypeScript中运行styled-components时,却被告知缺少Node.js的类型。

发生环境

    • styled-components : v3.3.3

 

    • TypeScript : v2.9.2

 

    React : 16.4.0

错误消息


ERROR in [at-loader] ./node_modules/styled-components/typings/styled-components.d.ts:117:44
    TS2503: Cannot find namespace 'NodeJS'.

解决办法

好像有一些解决方法。

解决方案①

安装@types/node库

npm install --save-dev @types/node

或者

yarn add -D @type/node

在tsconfig.json中添加typeRoots的记录


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

解决方案2

安装@types/node模块。

省略

在tsconfig.json中写入types


{
  "compilerOptions": {
    "types": ["node"]
  }
}

这似乎是解决找不到命名空间’NodeJS’的理论。
然而,即使如此,作者仍未能解决这个错误。

可以考慮第三個解決方案

固定styled-components的版本。

yarn remove styled-components
yarn add styled-components@3.1.6

这样一来,NodeJS的错误就解决了。


ERROR in [at-loader] ./node_modules/styled-components/typings/styled-components.d.ts:75:48
    TS2344: Type 'keyof T' does not satisfy the constraint 'string'.
  Type 'string | number | symbol' is not assignable to type 'string'.
    Type 'number' is not assignable to type 'string'.

出现了另一个错误。。。
在 styled-components@3.3.3 中,这个错误不再发生。

第四个解决方案。

声明/宣告 ‘NodeJS’.

这是最后的手段。
我直接编辑node_modules/styled-components/typings/styled-components.d.ts。


declare namespace NodeJS {
  export interface ReadableStream {

  }
}

将这个放入适当的位置,就不会出现错误了。

styled-components和TypeScript似乎没有太好的兼容性感觉…。