teambit / envs

Component development environments for the Bit community
https://bit.dev/bit/envs
Other
63 stars 9 forks source link

Duplicate identifier error from React Native @types when using styled-components in React with TypeScript (Solution included) #128

Closed JoshK2 closed 4 years ago

JoshK2 commented 4 years ago

Describe the bug

Most TS package as it's own @types. At times we might get conflicts between them. This error might happen when using React + TypeScript + styled-components (duplicate identifier error with a lot of types). An example of types error:

image

The problem is that @types/styled-components has a dependency on @types/react-native and it's causing the issue.

If you have this configuration and you don't get this error, please check that the skipLibCheck option in tsconfig is set to false (which is the default value).

Steps to Reproduce

  1. Create a React+TypeScript project.
  2. Install styled-components and @types/styled-components.
  3. Create a simple component that uses styled-components.
  4. Import the React TypeScript compiler from bit.
  5. Track and build the component. (You should see the error)

Screenshots, exceptions and logs

The dependencies from @types/styled-components package that include @types/react-native and causing the error:

"dependencies": {
        "@types/hoist-non-react-statics": "*",
        "@types/react": "*",
        "@types/react-native": "*",
        "csstype": "^2.2.0"
 },

How to solve this?

We can configure TypeScript the library we want to use when doing type checking using --types (list of names of type definitions to include).

To do it in Bit, you'll need to configure the Bit compiler's tsconfig. To do that, open your project's Bit configuration to override the compiler's default configuration (and add types).

"env": {
      "compiler": {
        "bit.envs/compilers/react-typescript@3.1.51": {
          "rawConfig": {
            "tsconfig": {
              "compilerOptions": {
                "types": ["node"]
              }
            }
          }
        }
      }
    },

And you need also to add @types/node as dev dependencies of your components, so it will build correctly in the Bit React-TypeScript compiler, to do so, just use the overrides option in Bit, like this:

"overrides": {
      "*": {
        "devDependencies": {
          "@types/node": "^12.12.29"
        }
      }
    }

Specifications