Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

displayName is broken since v1.10.3 #261

Open
psixdev opened this issue Nov 12, 2019 · 23 comments
Open

displayName is broken since v1.10.3 #261

psixdev opened this issue Nov 12, 2019 · 23 comments

Comments

@psixdev
Copy link

psixdev commented Nov 12, 2019

Hello. Starting with version 1.10.3, the plugin stops adding displayName to generated classes. This option worked in 1.10.2 and does not work in all subsequent versions. Here is a repository with a small example to verify this:
https://github.com/psixdev/babel-plugin-styled-components-bug

After loading the page, I get this html:
image

If I used version 1.10.2, it would be different:
image

Is this a bug in the library, or is something wrong in my application?

@psixdev
Copy link
Author

psixdev commented Nov 12, 2019

It seems that the plugin only works if I use import instead of require in my code. Is it possible to make the plugin work with require?

@frisbee09
Copy link

This is a duplicate of #243, I think. My current suspicion is something happening inside of @babel/core

@baybara-pavel
Copy link

baybara-pavel commented Nov 29, 2019

+1 for @babel/core changes
In my case, broken behavior reproduced with "babel-plugin-styled-components": "1.10.2", when I adding types to sc

// styled-components.ts
import * as styledComponents from 'styled-components';

import { Theme } from 'theme';

const {
  default: styled,
  css,
  createGlobalStyle,
  keyframes,
  ThemeProvider,
} = styledComponents as styledComponents.ThemedStyledComponentsModule<Theme>;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;

When I replace imports to the original lib in the target component displayName start work correctly

// import styled from 'utils/styled-components/styled-components'; <- displayName don't generates
import styled from 'styled-components'; //  <- displayName generates

In the beginning, I blame @babel/preset-typescript, but then I try to remove types and make just reexport for an experiment - nothing changed

// styled-components.js
import * as styledComponents from 'styled-components';

const { default: styled, css, createGlobalStyle, keyframes, ThemeProvider } = styledComponents;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;

Then I try to add ignoring for babel transpile of my styled-components reexport file and everything start working🎉 (except the types actually 😞)

// babel.config.js
module.exports ={
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['babel-plugin-styled-components', { ssr: false, displayName: true }],
    '@babel/plugin-transform-react-constant-elements',
    '@babel/plugin-proposal-export-default-from',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-object-rest-spread',
    // eslint-disable-next-line no-magic-numbers
    ['@babel/plugin-transform-runtime', { corejs: 2 }],
  ],
  overrides: [
    {
      test: /\.(ts|tsx)$/,
      presets: ['@babel/preset-typescript'],
      plugins: [
        'babel-plugin-ts-optchain',
        // eslint-disable-next-line no-magic-numbers
        ['@babel/plugin-transform-runtime', { corejs: 2 }],
      ],
    },
  ],
  ignore: ['./**/styled-components.js'],
};

I think the reason in that side effect:
babel transpiled my reexport file with styled-components ->
some property or method in sc changing and babel-plugin-styled-components can't find the right way to add displayName and it doesn't work correctly.

And suspicion to@babel\core was proved by that config:

// babel.config.js
module.exports ={
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['babel-plugin-styled-components', { ssr: false, displayName: true }],
  ],
};

In that case nothing work with the same simple styled-components reexport

// styled-components.js
import * as styledComponents from 'styled-components';

const { default: styled, css, createGlobalStyle, keyframes, ThemeProvider } = styledComponents;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;

@baybara-pavel
Copy link

baybara-pavel commented Nov 29, 2019

I found the workaround solution for that case. The reason in @babel\preset-env. Just overrides in babel config for my styled-components reexport with theme types and everything work

// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: [
    ['babel-plugin-styled-components', { ssr: false, displayName: true }],
    '@babel/plugin-transform-react-constant-elements',
    '@babel/plugin-proposal-export-default-from',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-object-rest-spread',
    // eslint-disable-next-line no-magic-numbers
    ['@babel/plugin-transform-runtime', { corejs: 2 }],
  ],
  overrides: [
  // --- The Saver:
    {
      test: /styled-components\.(ts|tsx)$/,
      presets: ['@babel/preset-react', '@babel/preset-typescript'],
    },
  // ---
    {
      test: /\.(ts|tsx)$/,
      presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
      plugins: [
        'babel-plugin-ts-optchain',
        // eslint-disable-next-line no-magic-numbers
        ['@babel/plugin-transform-runtime', { corejs: 2 }],
      ],
    },
  ],
};
// styled-components.ts
import * as styledComponents from 'styled-components';

import { Theme } from 'theme';

const {
  default: styled,
  css,
  createGlobalStyle,
  keyframes,
  ThemeProvider,
} = styledComponents as styledComponents.ThemedStyledComponentsModule<Theme>;

export { css, createGlobalStyle, keyframes, ThemeProvider };
export default styled;

image

@frisbee09
Copy link

I have the same snippet of typing from the styled-components documentation, I can try this override and see if it works for me also. Nice work @baybara-pavel :)

@baybara-pavel
Copy link

baybara-pavel commented Nov 29, 2019

@frisbee09 I hope it helps you to 🙂
Important: This workaround works only with "babel-plugin-styled-components": "1.10.2" with last 1.10.6 - still broken
Thanks to https://github.com/novli for insight

@frisbee09
Copy link

frisbee09 commented Nov 29, 2019

On further inspection, could this be broken due to #230
If the plugin is trying to detect a direct import from 'styled-components' and we're importing a "typed" re-export, we might be turning off the transpilation step inadvertently.

It might be that the plugin currently does not support a typed theme as specified in the styled-components documentation. I'll try looking into this.

This would also mean we're seeing the same issue as found in #238

@nihgwu
Copy link

nihgwu commented Dec 6, 2019

same issue here, although we don't use typescript, we just reexported styled-components in our theme system, as pointed by @frisbee09 , it's caused by #230 , then what should we do if we still want to reexport styled-components? maybe we could provide a config to disable the check? @probablyup

@ForestJohnson
Copy link

If you are using something like create-react-app, try this instead: https://styled-components.com/docs/tooling#babel-macro

@tshddx
Copy link

tshddx commented Mar 21, 2020

Is anyone else still experiencing this? I'm not getting component displayNames in my SC classes on babel-plugin-styled-components 1.10.7.

I tried downgrading to 1.10.2 to try the overrides workaround but it seems like styled-components@^5.0.1 depends on babel-plugin-styled-components ">= 1" and yarn seems to grab the latest 1.10.7 due to that dependency (I don't understand that at all, but it's a separate issue).

@joekrill
Copy link

@BadDox Yeah this is still affecting me. The babel macro alternative works, but I've been unable to get that to work in a mono-repo situation where my components are in a different package. Also I'm not sold on the idea of having to use a completely different import in that case.

@bradtgmurray
Copy link

Also running into this. Seems like I'm only running into issues when using ts-loader in my webpack config.

Example minimal repo reproducing the issue: https://github.com/bradtgmurray/babel-styled-components-test-repo

image

This branch fixes the issue by flipping from ts-loader to using babel to transpile my typescript.

https://github.com/bradtgmurray/babel-styled-components-test-repo/compare/fixed?expand=1

image

@tshddx
Copy link

tshddx commented Apr 5, 2020

@bradtgmurray That's really interesting. I'm not using TS at all and I have the problem. I have a minimal example built on a create-react-app in this thread: rebassjs/rebass#434 (comment)

@rozzzly
Copy link

rozzzly commented Apr 6, 2020

@bradtgmurray I just created a PR (#279) for another issue related to displayName but I'm curious if it might not resolve your issue as well.

@AssisrMatheus
Copy link

While using next.js. I fixed the issue by manually adding into package.json:

    "@babel/core": "7.8.4",
    "@babel/preset-env": "7.8.4",
    "babel-loader": "8.0.6",
    "babel-plugin-styled-components": "1.10.6",

This is my .babelrc.json

{
  "env": {
    "development": {
      "presets": ["next/babel"],
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "ssr": true,
            "displayName": true,
            "fileName": false
          }
        ]
      ]
    },
    "production": {
      "presets": ["next/babel"],
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "ssr": true,
            "displayName": true,
            "fileName": false
          }
        ]
      ]
    },
    "test": {
      "presets": [["next/babel"]],
      "plugins": [
        [
          "babel-plugin-styled-components",
          {
            "ssr": true,
            "displayName": true,
            "fileName": false
          }
        ]
      ]
    }
  }
}

@mkzxcvbnm
Copy link

import styled from 'styled-components'
replace to
import styled from 'styled-components/macro'

But I don't know what the side effects are

MilanLund added a commit to Kontent-ai-Learn/kontent-ai-learn-redoc that referenced this issue Jun 22, 2020
@ChrisKuBa
Copy link

Based on comparing 1.10.2 and 1.10.3
v1.10.2...v1.10.3

It seems that the problem starts here:

let localName = state.styledRequired

The local name is ignored when import statements are used and it is not cached.

export const importLocalName = (name, state, bypassCache = false) => {

importLocalName is used in isStyles.

export const isStyled = t => (tag, state) => {

isStyled is used here
: /* styled()`` */ (isStyled(t)(path.node.callee, state) &&

and is always false in my environment, so addConfig is never called and no displayName is configured.

By removing

let localName = state.styledRequired

the displayname will be rendered again.

@aurerua
Copy link

aurerua commented Mar 15, 2021

I couldn't find a working solution either.
In order to ease debugging until a solution emerges, I use the .attrs constructor like this:

const Content = styled.div.attrs({ 'data-testid': 'Content' })`
  margin-top: 21px;
`

@mgodwin
Copy link

mgodwin commented Jun 8, 2021

We were struggling with this as well. For us, I noticed the same thing as @baybara-pavel, that when we used import styled from 'styled-components' rather than import styled from 'src/styledComponents' the debug names appeared correctly in the DOM. We use typescript over here and originally defined a file that re-exported the constants from the original import for typing purposes. However, looking at the docs on the styled components site, it's actually not recommended or necessary to re-export everything from a src/styledComponents file anymore! https://styled-components.com/docs/api#styling-components

That's it! We're able to use styled-components just by using any original import.
import styled, { createGlobalStyle, css } from 'styled-components';

// theme is now fully typed

This is a double-win IMO, since folks on our team would accidentally use the original import all the time. Now I can get rid of that, and I have a much better debugging experience (and still retain types!). 🎊

@frisbee09
Copy link

frisbee09 commented Jun 8, 2021 via email

alirezamirian added a commit to alirezamirian/jui that referenced this issue Oct 13, 2021
It still doesn't work for most cases, since `styled` is not imported from `styled-components` for typing reasons.

More info: styled-components/babel-plugin-styled-components#261 (comment)

There is a suggestion here about how to stick with importing `styled` from `styled-components` and fix typing issue by augmenting `DefaultTheme` type.
https://styled-components.com/docs/api#styling-components
@iDVB
Copy link

iDVB commented Dec 23, 2021

We continue to have this issue with styles not being applied to the correct element. Have yet to find any solution other then to roll back to babel-plugin-styled-components@v1.10.3 in both our ui lib as well as all consuming projects.

Please help! No idea how to fix this and been limping along with 1.10.3 for months now.

@hayzey
Copy link

hayzey commented Jan 26, 2022

Using styled imported directly from styled-components instead of a re-exported module fixed it for us.

  • Broken - import styled from "./path/to/file"
  • Working - import styled from "styled-components"

@DanielCashlink
Copy link

DanielCashlink commented Jul 14, 2022

I never re-exported styled from anywhere, and this issue is still present with version 2.0.7

Nevermind, for me, I accidentally had babelrc: false in my webpack babel-loader config, so... user error, not an issue with this package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests