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!
I read here that this seems to be a code editor formatting problem. I found 4 possible solutions.
Configure the code editors extensions correctly (not sure what the issue is in this/your case though)
Press Opt+Shift+F and pick a code editor
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;
}
`;
const xyz = css`
body {
background: red;
}
`;
/* ↑ gets formatted by Prettier */
createGlobalStyle`
${xyz}
`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With