vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.04k stars 27k forks source link

Emotion styled doesn't work with SWC if labelFormat has [dirname] or [filename] #40091

Open tysian opened 2 years ago

tysian commented 2 years ago

Verify canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: Ubuntu 20.04.0 LTS Tue Aug 30 2022 12:34:01 GMT+0200 (Central European Summer Time)
Binaries:
  Node: 16.14.2
  npm: 7.17.0
  Yarn: 1.22.10
  pnpm: 7.9.5
Relevant packages:
  next: 12.2.6-canary.6
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0
  @emotion/react: 11.10.4
  @emotion/styled: 11.10.4

What browser are you using? (if relevant)

Chrome 104.0.5112.102

How are you deploying your application? (if relevant)

StackBlitz

Describe the Bug

Emotion styles are not applied if custom compiler.emotion.labelFormat is provided with [filename] or [dirname] in it.

  1. [dirname] is not replaced by actual directory name, it just stays as [dirname]
  2. [filename] causes that styles are not applied

image

Expected Behavior

Styles should applied correctly with custom labelFormat format.

Link to reproduction

https://stackblitz.com/edit/nextjs-a39s3g?file=pages/index.js

To Reproduce

  1. Install @emotion/react and @emotion/styled
    npm install @emotion/react @emotion/styled
  2. Create Next.js config file and set custom labelFormat, eg.

    
    // next.config.js
    const nextConfig = {
    compiler: {
    emotion: {
      sourceMap: true,
      // // This works fine
      // labelFormat: 'test-style__[local]',
    
      // // If [filename] is present styles are not applied
      // labelFormat: 'test-style__[filename]__[local]',
    
      // [dirname] variable is not replaced with actual directory name
      labelFormat: 'test-style__[dirname]__[filename]__[local]',
    },
    },
    };

module.exports = nextConfig;

3. Create custom styled component
```jsx
// pages/index.js
import styled from '@emotion/styled';

const StyledHello = styled.span`
  background: red;
  color: white;
`;
  1. Use it somewhere
    // pages/index.js
    export default function Home() {
    return (
    <main>
      <StyledHello>Hello</StyledHello>
    </main>
    );
    }
zvictor commented 2 years ago

Everything would be working properly with [filename] if it were replacing dots by a permitted character.

As a clear example, notice the use of the word Back.tsx multiple times as a css selector in the image below:

image

In the example above, If I manually replace Back.tsx by Back_tsx (in both occurences, definition and reference) the styles are then properly applied.

fennadew commented 2 years ago

I have the same issue