Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettier is not formatting my Styled Components code

I'm using Prettier, Eslint and Styled components in my project. The eslint rules are working so far. I don't know why, but Prettier is not formatting the styled components code.

Let me show you the example code that I am trying to fix:

This is the original code:

import { createGlobalStyle } from 'styled-components';

export const GlobalStyles = createGlobalStyle`
* {
box-sizing: border-box;
}
body {
font-size: 1.15em;
margin: 0;
}
`;

This is the code that I am expecting to get after formatting through Prettier and Eslint (but I am not) :

import { createGlobalStyle } from 'styled-components';

export const GlobalStyles = createGlobalStyle`
    * {
        box-sizing: border-box;
    }
    
    body {
        font-size: 1.15em;
        margin: 0;
    }
`;

My eslintrc.json:

{
    "env": {
        "browser": true,
        "es2021": true,
        "jest": true
    },
    "extends": [
        "next/core-web-vitals",
        "eslint:recommended",
        "plugin:jsx-a11y/recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": "latest",
        "project": "tsconfig.json",
        "sourceType": "module"
    },
    "plugins": ["@typescript-eslint/eslint-plugin", "react", "prettier"],
    "rules": {
        "react/jsx-uses-react": "off",
        "react/react-in-jsx-scope": "off",
        "no-shadow": "off"
    },
    "ignorePatterns": ["dist", "node_modules"]
}

My .prettierrc:

{
    "arrowParens": "always",
    "printWidth": 120,
    "semi": true,
    "singleQuote": true,
    "tabWidth": 4,
    "trailingComma": "es5",
    "useTabs": false
}

Any modification or recommendation will be more than welcome. So is there any way to solve this problem correctly? Thanks for any help!

like image 918
Javier Sebastián Fernández Avatar asked Oct 26 '25 08:10

Javier Sebastián Fernández


1 Answers

I read here that this seems to be a code editor formatting problem. I found 4 possible solutions.

  1. Configure the code editors extensions correctly (not sure what the issue is in this/your case though)

  2. Press Opt+Shift+F and pick a code editor

  3. Do a workaround as suggested in the github link above, where you do the following:

import * as styled from 'styled-components';

export default styled.createGlobalStyle`
  body {
    margin: 0;
  }
  code {
    font-family: comic-sans-ms; 
  }
`;
  1. Another workaround:
const xyz = css`
  body {
    background: red;
  }
`;
/* ↑ gets formatted by Prettier */

createGlobalStyle`
  ${xyz}
`;
like image 173
ce-loco Avatar answered Oct 28 '25 22:10

ce-loco