GithubHelp home page GithubHelp logo

styled-components / babel-plugin-styled-components Goto Github PK

View Code? Open in Web Editor NEW
1.1K 31.0 140.0 2.47 MB

Improve the debugging experience and add server-side rendering support to styled-components

License: MIT License

JavaScript 100.00%
styled-components minification babel babel-plugin ssr

babel-plugin-styled-components's Introduction


Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress ๐Ÿ’…

downloads: 600k/month Discord gzip size module formats: umd, cjs, esm Code Coverage

Upgrading from v5? See the migration guide.

Utilizing tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allow you to write actual CSS code to style your components. It also removes the mapping between components and styles โ€“ using components as a low-level styling construct could not be easier!

const Button = styled.button`
  color: grey;
`;

Alternatively, you may use style objects. This allows for easy porting of CSS from inline styles, while still supporting the more advanced styled-components capabilities like component selectors and media queries.

const Button = styled.button({
  color: 'grey',
});

Equivalent to:

const Button = styled.button`
  color: grey;
`;

styled-components is compatible with both React (for web) and React Native โ€“ meaning it's the perfect choice even for truly universal apps! See the documentation about React Native for more information.

Supported by Front End Center. Thank you for making this possible!


See the documentation at styled-components.com/docs for more information about using styled-components!

Quicklinks to some of the most-visited pages:


Example

import React from 'react';

import styled from 'styled-components';

// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

function MyUI() {
  return (
    // Use them like any other React component โ€“ except they're styled!
    <Wrapper>
      <Title>Hello World, this is my first styled component!</Title>
    </Wrapper>
  );
}

This is what you'll see in your browser:


Looking for v5?

The main branch is for the most-current version of styled-components, currently v6. For changes targeting v5, please point your PRs at the legacy-v5 branch.


Built with styled-components

A lot of hard work goes into community libraries, projects, and guides. A lot of them make it easier to get started or help you with your next project! There are also a whole lot of interesting apps and sites that people have built using styled-components.

Make sure to head over to awesome-styled-components to see them all! And please contribute and add your own work to the list so others can find it.


Contributing

If you want to contribute to styled-components please see our contributing and community guidelines, they'll help you get set up locally and explain the whole process.

Please also note that all repositories under the styled-components organization follow our Code of Conduct, make sure to review and follow it.


Badge

Let everyone know you're using styled-components โ†’ style: styled-components

[![style: styled-components](https://img.shields.io/badge/style-%F0%9F%92%85%20styled--components-orange.svg?colorB=daa357&colorA=db748e)](https://github.com/styled-components/styled-components)

Contributors

This project exists thanks to all the people who contribute. [Contribute].


Backers

Thank you to all our backers! ๐Ÿ™ [Become a backer]


Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]


License

Licensed under the MIT License, Copyright ยฉ 2016-present Glen Maddern and Maximilian Stoiber.

See LICENSE for more information.


Acknowledgements

This project builds on a long line of earlier work by clever folks all around the world. We'd like to thank Charlie Somerville, Nik Graf, Sunil Pai, Michael Chan, Andrey Popp, Jed Watson & Andrey Sitnik who contributed ideas, code or inspiration.

Special thanks to @okonet for the fantastic logo.

babel-plugin-styled-components's People

Contributors

0x80 avatar achingbrain avatar artnattapat avatar bpierre avatar chalbert avatar dependabot[bot] avatar epilande avatar fatfisz avatar healtheloper avatar kitten avatar maisano-patreon avatar mbrowne avatar mellamopablo avatar mxstbr avatar nickhudkins avatar niklasgrahl avatar phyllisstein avatar quantizor avatar re-fort avatar robin-drexler avatar salper avatar samatar26 avatar saravieira avatar satya164 avatar sfishel18 avatar siddharthkp avatar silverlight513 avatar vdanchenkov avatar zapkub avatar zaubernerd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

babel-plugin-styled-components's Issues

Support require() calls

Plugin will not work properly with Typescript

from styled-components/styled-components#1168 (comment) (Include workaround)

import default in Babel and Typescript have a little different. The result of Typescript come with .default

Reproduce

  1. Clone this repo https://github.com/zapkub/nextjs-typescript-styled-component
  2. Modify index.tsx line 2 from StyledComponents to styled and remove line no. 3
  3. Run project
  4. Plugin will be broken

Detail

[email protected]
[email protected]
[email protected]

Different class names when rendering on client vs server

I'm trying to add SSR to a project based on Create React App. On my backend I got it to render the correct CSS by using this babel plugin and adding ssr: true to my .babelrc file, but now the class names are not the same as when they're client rendered.

I'm using the newest version 2.0.0 on both the client and server, but since I haven't ejected CRA, I can't add a babel loader to it and I'd prefer not to eject.

The client class names has a sc- prefix and looks like sc-bdVaJa jfEfSr, while the server rendered ones do not and also have different hashes.

Is this possible to fix? And should it be? I'm thinking now that having two different ways of transpiling my code on the client and server will lead to trouble in other places eventually. But I'm also curious as to why the hashes are different, I'm guessing this plugin handles it differently than the main styled-components does?

Identifiers in test fixtures affected by tests order.

Looks like currently tests runs in alphabetical order and if I create test in the middle, it affects ids generated for components in all tests which runs after it.

My ideas are: introduce internal id counter reset method or explicitly set order of tests.

Minification strips whitespace for wrapped lines

Context

Prettier 1.5.0 introduces support for formatting styled-components output. One of the changes it makes is wrapping long lines to the next line.

The minification setting in babel-plugin-styled-components strips out this whitespace entirely.

Test Case

Input test.js:

import styled from 'styled-components';

const output = styled.li`
  animation: really-really-really-really-really-really-long-name 2s linear infinite;
`;

console.log(output.componentStyle.rules);
$ jest test.js
[ 'animation: really-really-really-really-really-really-long-name 2s linear infinite;' ]

Output from prettier test.js, note how there isn't a space between linear and infinite:

import styled from 'styled-components';

const output = styled.li`
  animation: really-really-really-really-really-really-long-name 2s linear
    infinite;
`;

console.log(output.componentStyle.rules);
$ jest test.js
[ 'animation: really-really-really-really-really-really-long-name 2s linearinfinite;' ]

With minification turned off, the whitespace is preserved:

$ jest test.js
[ '\n  animation: really-really-really-really-really-really-long-name 2s linear\n    infinite;\n' ]

Need better way to determine componentId

I was able to get duplicates with create-react-app setup because it uses babel-loader with cache enabled.

Considering other options.

  • path.hub.file.code
  • path.hub.file.sourceFileName and last part of path.hub.file.sourceRoot
  • path.hub.file.filename

code hash is the most reliable, but it will break if we have two files with exactly the same source. For other options we'll have ask user to configure babel to provide sourceRoot and fileName

"React attempted to reuse markup error" when using withComponent

I'm doing this:
const Button = Input.withComponent('button')

And getting this error on console:

React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) ><button class="sc-bwzfXH dsgxen" data-r
(server) ><button class="sc-bxivhb kxuNeJ" data-r

And it's only showing if use withComponent() method in styled-components

Next.js: `TaggedTemplateExpression` not run when `env`s are defined in .babelrc

I'm seeing something very strange and I don't know why its happening.

If you have a .babelrc file defined as so:

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

then when you build the app, the TaggedTemplateExpression part of babel-plugin-styled-components is never called. That results in code that looks like this:

var _templateObject = (0, _taggedTemplateLiteral3.default)(['\n  color: red;\n  font-size: 50px;\n'], ['\n  color: red;\n  font-size: 50px;\n']);

var Title = _styledComponents2.default.h1(_templateObject);

rather than the expected:

var Title = _styledComponents2.default.h1.withConfig({
  displayName: 'pages__Title',
  componentId: 'tr8ekl-0'
})(['color:red;font-size:50px;']);

I replicated it using Next.js example with-styled-components.

Could someone verify that they see the same thing?

  • download that example linked above
  • change its .babelrc file to the one above
  • do a npm run build
  • look at the /.next/dist/pages/index.js file to see if the styled component has a withConfig

Contextual Overrides do not work with preprocess

Hello, using preprocess for this code:

const Link = styled.a`
  color: inherit;
  text-decoration: none;
  &:hover, &:active {
    text-decoration: underline;
  }
`
const P = styled.p`
  ${ Link } {
    text-decoration: underline;
  }
`

Will generate the following error:
image

Here's the code generated when preprocess is on:

var Link = __WEBPACK_IMPORTED_MODULE_1_styled_components_no_parser___default.a.a.withConfig({
  displayName: 'Dialog__Link',
  componentId: 's1djntd5-6'
})([['{color: inherit;-webkit-text-decoration: none;text-decoration: none;}'], [':hover,'], [':active{-webkit-text-decoration: underline;text-decoration: underline;}']]);
var P = __WEBPACK_IMPORTED_MODULE_1_styled_components_no_parser___default.a.p.withConfig({
  displayName: 'Dialog__P',
  componentId: 's1djntd5-7'
})([[' ', Link, '{-webkit-text-decoration: underline;text-decoration: underline;}']]);

And when preprocess is off:

var Link = __WEBPACK_IMPORTED_MODULE_1_styled_components__["c" /* default */].a.withConfig({
  displayName: 'Dialog__Link',
  componentId: 's1djntd5-6'
})(['color: inherit;text-decoration: none;&:hover, &:active {text-decoration: underline;}']);
var P = __WEBPACK_IMPORTED_MODULE_1_styled_components__["c" /* default */].p.withConfig({
  displayName: 'Dialog__P',
  componentId: 's1djntd5-7'
})(['', ' {text-decoration: underline;}'], Link);

Invalid checksum

I am using the babel plugin 1.1.5 with styled components 2.1.0. I have placed a ssr: true in both the client and the server babel configs.

However, I always see this mismatch in checksum:

(client) P gradient-container___default-s1b1hs7t-
(server) P gradient-container-s1b1hs7t-0 ieOpth"

This tells me that the plugin is enabled for both the client and server, but the client consistently has this __default string as part of the class name. Where is this coming from?

Missing babel-types dependency?

I'm building a storybook based module and coming up against this error:

Module build failed: Error: Cannot find module 'babel-types'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/path/to/project/node_modules/babel-plugin-styled-components/lib/visitors/minify.js:7:19)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

It looks like /src/visitors/minifiy.js does indeed try to import babel-types but the dependency is missing from this module's package.json file. Any chance of adding it?

Option for ssr clashes with displayName

If you set ssr: true the component names are not part of the classes anymore. Even if you add displayName: true.

If this is intentional it should be mentioned I guess.

How to install

I wanted to minimize my css, as I have seen issues closed in react-boilerplate, I thought it was solved by this plugin.

I have tried to install using npm and git+ssh, I know it's written WIP but is there a way to test the minification or it's not ready at all ?

Integration with typescript

I'm using babel to transpile ES6 made by typescript to ES5. And it looks like this plugin doesn't work at all in this case.

typescript v2.2.2
styled-components v2.0.0-15
awesome-typescript-loader v3.1.2
babel-plugin-styled-components v1.1.4

Using 2.0.0-17 of styled-components doesn't correctly extract styles for extended classes serverside

With the following code

const Paragraph = styled.p`
  font-size: 24px
`;

const Title = styled(Paragraph)`
  color: 'red';
`;

const Example = props => {
  const {text} = props;

  return (
    <Title>{Hello World}</Title>
  );
};

The color and font-size rules are split into two different classes but only the color class is sent from the server. When the page renders styled-components correctly renders both styles.

Here is the config babel is using

["styled-components", {
      "minify": true,
      "ssr": true
    }]

Update to new syntax

As of styled-components/styled-components#227 the new syntax for the private API is .withConfig:

const Box = styled.div.withConfig({ displayName: 'Box', componentId: 'Button_asdf123' })`
  styles: here;
`

This avoids issues on ReactNative where target would before need to be View (no string) and we'd need to import it, which would've made everything much more compilcated.

I'm thinking about switching this to be .__config to make sure people don't accidentally use it, but that's a trivial change. We should get this changed asap!

Clarifications of "improved debugging" and component names.

Hi, I implemented this plugin on the client side of our application. (This may have been my first mistake). Because I was hoping to get the Devtools names functionality i.e ComponentName instead of styled.div in my DomTree, as well as classNames like sc-ComponentName.

Unfortunately none of these things seem to be happening. I still have styled.div lying around and classes are in the vein of sc-jfkdl poijl. Not what I was expecting. Could you clarify that if I'm doing something like:

const MyComponent = styled.div`
  color: red;
`;

I should be seeing either <MyComponent ...> in my React Devtool and <div className="sc-MyComponent"> in my element inspector? Or is this functionality for server side generation early? If I should be expecting to see that any ideas what I might be doing wrong? I know the Readme states the plug in is for serverside usage only but it's not 100% clear if that's solely for server side rendering or all the additional functionality underneath that section.

Thanks!

Fix identifiers

I forgot that the identifiers actually don't need to be added to the underlying component but to the actual component:

const Test = styled.div``;
Test.identifier = 1;

What I do right now (which is wrong) is this:

const Test = function() {
  const c = styled.div``;
  c.identifier = 1;
}();

Switching to the first one will be a bit harder, and since we're still exploring possible other syntaxes I'm going to invest a large amount of time into fixing this, since we probably won't keep it around anyway. /cc @geelen

styled-components/native support

As-is, this plugin does not appear to detect usages of styled when imported from styled-components/native instead of styled-components.

I'm specifically interested in the displayName support to make debugging easier.

[v1.0.1] Possible bug: debug displayname (and styled-components v2).

Hello,

I just upgraded (babel-plugin-styled-components) from v:1.0.0 to v:1.0.1 and now the plugin dons't add the components' name to the class name.

Div with v:1.0.1: <div data-reactroot="" class="c4dx7z-0 bUnYA">
Div with v:1.0.0: <div data-reactroot="" class="app__DivFlexWrapper-14dsmrv jSMEYv">

Using:
"styled-components": "~2.0.0-8"

Babelrc:
.babelrc
{
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"styled-components",
"react-hot-loader/babel"
]
}

I know that this plugin might not be compatible with styled components 2, but would like to let you know and see if I'm doing something wrong.

Styled component displayName won't show up in React Dev Tools

Hello,

I followed the instructions in the README file and created a .babelrc, refer the styled-components plugin, but the names are not shown.

{
   "plugins": [ "styled-components" ],
   "presets": [ "react-app" ]
}

I know it reads my .babelrc file, because when I leave out the presets, I get a bunch of error messages.

When I inspect my styled-components I can also see the prefix sc-. So that seems to work.
Another interesting behavior occurs when I try to set displayName true:

{
   "plugins": ["styled-components", {
      "displayName": true
    }],
   "presets": [ "react-app" ]
}

Then I get the following error:

yarn start v0.23.4
$ babel-node scripts/start.js
/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/plugin.js:131
      throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
      ^

Error: Plugin 1 specified in "/Users/.../.babelrc" provided an invalid property of "displayName"
    at Plugin.init (/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/plugin.js:131:13)
    at Function.normalisePlugin (/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
    at /Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
    at Array.map (native)
    at Function.normalisePlugins (/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
    at OptionManager.init (/Users/.../node_modules/babel-register/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at compile (/Users/.../node_modules/babel-register/lib/node.js:103:45)
    at loader (/Users/.../node_modules/babel-register/lib/node.js:144:14)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/..../node_modules/babel-register/lib/node.js:154:7)
error Command failed with exit code 1.

I'm using TypeScript 2.3.2, my setup is based on react-scripts but with webpack 2.6.1

Thanks ๐Ÿ˜€

Uncaught TypeError: _styledComponents2.default.div.withConfig is not a function

I added the plugin without any additional config to my babelrc:

{
    "presets": [
        "es2015",
        "react",
        "stage-2"
    ],
    "plugins": [
        "transform-class-properties",
        "styled-components",
        [
            "module-resolver",
            {
                "root": [
                    "./src/javascript"
                ],
                "alias": {
                    "actions": "actions",
                    "components": "components",
                    "constants": "constants",
                    "config": "config",
                    "libs": "libs",
                    "store": "store",
                    "styles": "styles",
                    "utils": "utils",
                    "middleware": "middleware"
                }
            }
        ]
    ]
}

Everything worked perfectly before adding the plugin and now I'm getting this error:
Uncaught TypeError: _styledComponents2.default.div.withConfig is not a function

The code its throwing on is:

const App = styled.div`
        min-height: 100%;
        background-position: center center;
        font-size: 1em;

        ${media.mobile`
            font-size: 1.05em;
        `}
        ${media.largeMobile`
            font-size: 1.2em;
        `}
        ${media.tablet`
            font-size: 1.3em;
        `}
        ${media.desktop`
            font-size: 1.4em;
        `}
        ${media.largeDesktop`
            font-size: 1.25em;
        `}
`;

Minify CSS

Currently all CSS used in styled-components is unminified.
As @mxstbr suggested on Gitter, this Babel plugin could take care of minifying the CSS.
Perhaps only when process.env.NODE_ENV === 'production'?

Alternatively, this could be a babili plugin.

Related to styled-components/styled-components#284

Doesn't work with create-react-app (pre-eject)

Thanks so much for everyone's hard work on this amazing styled-components ecosystem.

I have a small component library that I set up using create-react-app and styled-components and could not get this plugin to work at all without doing an npm run eject and then it worked exactly as advertised.

Has anyone else experienced this or, more importantly, figured out a way to get the plugin working without ejecting? This is probably more of a create-react-app issue, but given the popularity of it, it would be nice to have a solution and/or a note about it not working in this Readme.

Thanks again!

How does preprocess work?

Hi ๐Ÿ‘‹ ,

I haven't had a chance to look at the code but thought i'd reach out of an explanation in case it's quicker. I was reading styled-components/styled-components#59, because I'm interested in performance enhancements that could be made by exporting static styles for the browser to cache and only parse dynamic styles. It sounded like some json representation was discussed, is this what the preprocessor does?

Component display name appears twice in single CSS class

When using babel-plugin-styled-components, the display names in the identifying CSS classes are being doubled up. It appears this problem may actually go deeper and be caused by the display names themselves being doubled.

This screenshot is from the React dev tools of a very simple app I put together to demonstrate this problem. You can find the code here.

screen shot 2017-07-10 at 5 54 48 pm

I now have 3 sites where I am attempting to use this plugin and all behave similarly. The primary site uses a custom webpack config, the others use create-react-app.

Thanks for having a look at this. We are very excited to have the display names in the CSS (once...).

[V1] Comment and whitespace from css are still present in distribution build.

I can see many css comments compiled in my distribution build which increase the global size.

image

Version

1.0.0

Reproduction

http://www.webpackbin.com/NkoxEJM9G

Steps to reproduce

const HelloWorld = styled(HelloWorldUnStyled)`
  border-bottom: 2px solid blue;
  /* this comment will be distributed */
  border-top: 2px solid yellow;
  /* with all the spaces as well                                                            */
  border-bottom: 2px solid green;
`;

Expected Behavior

var a=b(c)`border-bottom: 2px solid blue;border-top: 2px solid yellow;border-bottom: 2px solid green`;

Actual Behavior

var a=b(c)`border-bottom: 2px solid blue;/* this comment will be distributed */border-top: 2px solid yellow;/* with all the spaces as well                                                            */border-bottom: 2px solid green;
`;

Module build failed after update from 1.1.4 to 1.1.5

I understand this Error throw from another module. Maybe stylis or maybe styled-jsx.

But 1.1.5 is a patch semver update. It introduce a break change.

I downgrade to 1.1.4. It no problem.

Module build failed: Error: /pages/room.js?entry: Nesting detected at 11:34. Unfortunately nesting is not supported by styled-jsx.
    at Function.disableNestingPlugin (/node_modules/styled-jsx/dist/lib/style-transform.js:19:13)
    at proxy (/node_modules/stylis/stylis.js:1133:30)
    at compile (/node_modules/stylis/stylis.js:679:10)
    at compile (/node_modules/stylis/stylis.js:319:17)
    at stylis (/node_modules/stylis/stylis.js:1270:16)
    at preprocessHelper (/node_modules/babel-plugin-styled-components/lib/css/preprocessUtils.js:95:43)
    at exports.default (/node_modules/babel-plugin-styled-components/lib/css/preprocess.js:12:96)
    at exports.default (/node_modules/babel-plugin-styled-components/lib/visitors/templateLiterals/preprocess.js:48:41)
    at exports.default (/node_modules/babel-plugin-styled-components/lib/visitors/templateLiterals/index.js:23:30)
    at PluginPass.TaggedTemplateExpression (/node_modules/babel-plugin-styled-components/lib/index.js:21:40)
    at newFn (/node_modules/babel-traverse/lib/visitors.js:276:21)
    at NodePath._call (/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/node_modules/babel-traverse/lib/index.js:114:17)

My code used styled-components

const StyledGrid = styled(Grid)`
  .am-flexbox .am-flexbox-item .am-grid-item-content .am-grid-item-inner-content .am-grid-icon {
    width: 33%;
    height: 33%;
  }
`

const ListCenterItem = styled(List.Item)`
  .am-list-line .am-list-content {
    text-align: center;
  }
`

const ListCenterLargeItem = styled(ListCenterItem)`
  .am-list-line .am-list-content {
    font-size: .5rem;
  }
`

const ShareQRCode = styled(Result)`
  .am-result-pic {
    width: auto;
    height: auto;
    margin: 0;
    line-height: inherit;
    background-size: auto auto;
  }
`

My babel setting

{
    "presets": [
        "next/babel"
    ],
    "plugins": [
        [
            "import",
            [
                {
                    "libraryName": "antd-mobile"
                },
                {
                    "libraryName": "recompose",
                    "libraryDirectory": "",
                    "camel2DashComponentName": false
                }
            ]
        ],
        [
            "styled-components",
            {
                "ssr": true,
                "displayName": true,
                "preprocess": true
            }
        ]
    ]
}

SSR with styled.extend throws error

minimal example (its with-styled-component next example)

What I do

  1. yarn run dev
  2. load page
  3. reload page

Get error

Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
 (client) ="1"><div class="sc-bdVaJa iNGvMq" data-
 (server) ="1"><div class="sc-jzJRlG fzsTbP" data-

Possible bug with minification

I ran into this strange problem today which I think has to do with minification done by the plugin. I was trying to compile this TypeScript file (note the missing semicolon at the end of the template literal). This plugin is applied together with other babel plugins after the typescript compilation step in webpack.

import * as styledComponents from 'styled-components';
const styled = styledComponents.default;

const contentLeft = 'globalContentLeft';
const contentRight = 'globalContentRight';
const globalContentTop = 'globalContentTop';
const globalContentBottom = 'globalContentBottom';

const menuTop = 'rankingsMenuTop';
const menuBottom = 'rankingsMenuBottom';
const contentTop = 'rankingsMenuContentTop';
const contentBottom = 'rankingsMenuContentBottom';

const Grid = styled.main`
  grid-column: ${contentLeft} / ${contentRight};
  grid-row: ${globalContentTop} / ${globalContentBottom};

  display: grid;
  grid-template-rows: [${menuTop}] 250px
                      [${menuBottom} ${contentTop}] auto
                      [${contentBottom}]
`;

export default Grid;

If I leave minification on (default), this is the eventual style tag injected into the DOM. Note the missing grid-template-rows CSS property:

.kMCkPy {
  grid-column: globalContentLeft / globalContentRight;
  grid-row: globalContentTop / globalContentBottom;
  display: grid;
}

If I set minify: false, I get the expected output with the grid-template-rows property:

.jXSKOK {
  grid-column: globalContentLeft / globalContentRight;
  grid-row: globalContentTop / globalContentBottom;
  display: grid;
  grid-template-rows: [rankingsMenuTop] 250px [rankingsMenuBottom rankingsMenuContentTop] auto [rankingsMenuContentBottom];
}

However, if I turn minification back on but also insert the missing semicolon at the end of the template literal, I get the expected output.

.cZjrpn {
  grid-column: globalContentLeft / globalContentRight;
  grid-row: globalContentTop / globalContentBottom;
  display: grid;
  grid-template-rows: [rankingsMenuTop] 250px[rankingsMenuBottom rankingsMenuContentTop] auto[rankingsMenuContentBottom];
}

I used styled-components v 2.0.1 and babel-plugin-styled-components v 1.1.4.

//-style comments are mangled by the plugin

When using line comments, they get their newline stripped by the minification and they become an erroneous selector.

I was also not able to turn off minify with the plugin options. (config error)

I propose that minification be disabled until #26 lands, that will be much more useful and correct.

Information about new warning in documentation

โš ๏ธ This plugin is only necessary if you're server-side rendering, you can use styled-components perfectly fine without it! โš ๏ธ

I was using plugin v1.0.0 to compress my distribution build. Is this included by default in styled-components@? without any plugin ?

Does this work with Vue (vue-styled-components)

Hi

I was wondering if this also works with vue-styled-components.

I tried it and I am getting weird errors concerning my style.js files with things like const Section = styled('div', styleProps)...

I would like to use the debugging feature which adds a identifiable class name in dev mode.

Thanks for any answer.
Cheers

Questions about componentId

Currently with { ssr: true, displaName: false } component id gets generated with component name Component-137hlza. Should we change it to s-137hlza if displayName is disabled? I guess human-readable name here is solely for debug purposes?

Support different import names

Currently, this breaks the babel plugin:

import s from 'styled-components'

Instead of hard-coding and checking for the styled keyword, we should be looking for the import declaration and getting the variable name. (what I do here and here in the stylelint processor)

Component name does not show

//.babelrc
{
"presets": ["es2015", "react","env"],
"plugins": [
["styled-components-named"]
]
}
//react DevTools
instead of there are 'styled.div'
Also doesnot work with 'babel-plugin-styled-components'

Deduplicate rules when using extend

Feel free to close this if I'm wrong, but it seems like when a styled component is extended, the new styles are simply appended to the end of the original styles.

It would be cool if this babel plugin could dedupe staticly defined properties that have multiple instances within the same styling context.

Cannot pass plugin options?

NPM install of babel-plugin-styled-components with following .babelrc:

{
  "plugins": ["styled-components", {
      "displayName": false
    }]
}

When run with babel-cli (or via webpack) I get the following:

Error: Plugin 1 specified in ".babelrc" provided an invalid property of "displayName"

This is the same for all options (ssr, minify, displayName). When passing no options, the plugin appears to be working as expected with friendly component names showing via inspector/dev tools. What am I doing wrong?

Error "withConfig is not a function"

Hi,
I just installed the plugin as described but when I try to bundle code using webpack the next error arise:

TypeError: _styledComponents2.default.h1.withConfig is not a function

Am I missing something? Any help?

Preprocessing mangling css

I've got the following code using styled-components, polished and a media query function based on the one specified in the styled-components docs (https://www.styled-components.com/docs/advanced#media-templates).

const Wrapper = styled.div`
  ${clearFix()}
  margin-top: ${rem('10px')};

  ${media.bpSmall`
    margin-top: 0;
  `}
`;

When using the babel-plugin on the following settings:

["styled-components", {
  "ssr": true,
  "preprocess": false,
  "minify": false
}]

It works perfectly fine and I get the expected output:

/* sc-component-id: Header__Wrapper-ceoji3-0 */
.Header__Wrapper-ceoji3-0 {}

.BXvSp{margin-top: 0.625rem;}.BXvSp::after{clear: both;content: "";display: table;}@media (min-width: 34.375rem){.BXvSp{margin-top: 0;}}

When turning on preprocessing I get the following output:

/* sc-component-id: Header__Wrapper-ceoji3-0 */
.Header__Wrapper-ceoji3-0 {}

.lfbwyd{&::after {
  clear: both; content: ""; display: table;
};margin-top: 0.625rem;;}.lfbwyd@media (min-width: 34.375rem){.lfbwyd{
    margin-top: 0;
  ;}}

I've got more examples of similar breaks if it would be helpful.

[email protected]
[email protected]
[email protected]

`preprocessor` adds extra className when using templated media queries

I ran into an issue when implementing the templated media queries as explained the styled-components/styled-components repo.

If I enable preprocess, the classNames is added before the media query:

{
  "presets": ["next/babel", "es2015", "react"],
  "plugins": [["styled-components", { "ssr": true, "displayName": true, "preprocess": true }]],
}

screen shot 2017-07-13 at 14 40 57

This causes the media query to not work. When I disable preprocess, everything works as expected:

{
  "presets": ["next/babel", "es2015", "react"],
  "plugins": [["styled-components", { "ssr": true, "displayName": true, "preprocess": false }]],
}

screen shot 2017-07-13 at 14 41 48

Bug with custom default import name + component selector

import React from 'react';
import { create as render } from 'react-test-renderer';
import styledSc, { ThemeProvider } from 'styled-components';

const Ancestor = styledSc.div`
  color: red;
`;

const Child = styledSc.div`
  background-color: ${p => p.theme.backgroundColor};
  font-size: ${p => p.fontSize}px;
`;

const Parent = styledSc.div`
  border: 1px solid ${p => p.theme.borderColor};
  color: ${p => p.color};

  ${Child} {
    font-family: monospace;
  }
`;

const theme = {
  backgroundColor: 'cornflowerblue',
  borderColor: 'antiquewhite',
};

const themeVariant = {
  backgroundColor: 'mistyrose',
  borderColor: 'gainsboro',
};

const getVariant = useVariant => (
  <ThemeProvider theme={useVariant ? themeVariant : theme}>
    <Ancestor>
      <Parent color={useVariant ? 'red' : 'black'}>
        <Child fontSize={useVariant ? 10 : 12} />
      </Parent>
    </Ancestor>
  </ThemeProvider>
);

const instance = render(getVariant());

Results in the error "TypeError: Cannot call a class as a function".

Changing styledSc to styled makes the error go away.

displayName and filenames with dots

If the filename for your styled-component is e.g. countdown.styled.js you get a classes like "countdown.styled__Item-xwcjw2-1 ellRMD". Since this contains a dot it breaks references to that component.

Example:

export const Item = styled.div`
  display: inline-block;
`

export const Num = styled.div`
  border-right: 1px solid red;
  
  ${Item}:last-child & {
    border-right: 0;
  }
`

const Countdown = () => <div>
  <Item><Num>1</Num> day</Item>
  <Item><Num>2</Num> hours</Item>
  <Item><Num>3</Num> minutes</Item>
</div>

The example works with displayName: false but not with displayName: true.
Removing the dot from the filename also fixes the problem.

I suggest stripping dots and other reserved characters from the classnames.

Conflict with 'babel-plugin-add-react-displayname'

This works (it shows the component's name):

  "plugins": [
    [
      "styled-components", {
        "ssr": true
      },

      "add-react-displayname"
    ]

This doesn't:

  "plugins": [
    [
      "add-react-displayname",

      "styled-components", {
        "ssr": true
      }
    ]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.