Giter VIP home page Giter VIP logo

gatsby-plugin-linaria's Introduction

gatsby-plugin-linaria

npm npm downloads

Gatsby plugin for styling with Linaria

Install

Install the plugin and Linaria:

yarn add gatsby-plugin-linaria @linaria/core @linaria/react

Next, add the plugin to gatsby-config.js:

plugins: [
  'gatsby-plugin-linaria',
]

TypeScript

If you're using TypeScript, make sure to include gatsby-plugin-typescript before gatsby-plugin-linaria in your config:

plugins: [
  'gatsby-plugin-typescript',
  'gatsby-plugin-linaria',
]

See #13 for more details.

Customize Loader Options

You can customize linaria loader options

{
  resolve: 'gatsby-plugin-linaria',
  options: {
    loaderOptions: {
      // ... Specify options here
    },
  },
}

Critical CSS Extraction

GatsbyJS & Linaria extract your stylesheet and inject into the <head> by default. So, you don't need to worry about the SSR & FOUC.

However, the extracted stylesheet would be huge for large site, because it includes css used by whole pages/components

This plugin provide an option extractCritical that use @linaria/server API behind the scene

{
  resolve: 'gatsby-plugin-linaria',
  options: {
    extractCritical: true, // false by default.
  },
}

When you opt-in this feature, only Critical CSS is injected into the <head>. And loading full CSS will be deferred for later paint or navigations.

Lighthouse might complain you have duplicated style rules. (It's OK)

See this for more detailed explanation.

Changelog

See CHANGELOG.md

LICENSE

MIT


Happy styling! 🎨

gatsby-plugin-linaria's People

Contributors

cometkim avatar dependabot-preview[bot] avatar diegohaz avatar krrish96 avatar lgtm-com[bot] avatar renovate[bot] avatar silvenon avatar tsuki-lab 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

Watchers

 avatar  avatar  avatar

gatsby-plugin-linaria's Issues

Breaks Gatsby v3

This line:

delete newConfig.resolve?.alias?.['@reach/router'];

Created to solve #19 breaks Gatsby v3, which relies on that alias now that they've vendored reach-router. https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v2-to-v3/#reach-router

Removing the line allows the plugin to work in v3, but I'm not sure if it re-introduces the styled problem with Gatsby Link. Regardless, without the change, this will break a lot of folks moving to v3.

Option to disable SSR?

Is there a way to disable SSR for this plugin? Linaria outputs actual .css files rather than adding style tags inline. SSR i feel like this plugin defeats the purpose of using Linaria as an CSS-in-JS solution when the output is similar to Emotion or styled-components.

I switched from Emotion to Linaria to get .css files, i figure .css files are easier to cahce for the client rather than pasting styles on the HTML head tag.

should critical be a the top of head?

first of all, thanks for creating this plugin, i love it :)

i have a question regarding this bit:

https://github.com/silvenon/gatsby-plugin-linaria/blob/a52b2cb3a2b0e59847ef0fdb291357008e1a325c/src/gatsby-ssr.js#L35-L43

i'm adding a reset by just doing import 'reset.css' and having gatsby inject it into the head. the same with some @font-faces.

when using this plugin, the linaria's critical css is inserted before any other css i've added.

this instinctively feels the wrong way round to me – i was wondering what your reason was for choosing this order?

Unexpected token

I tried to use this on gatsby-default-starter but it's throwing Unexpected token error. It seems that linaria/loader is being processed before babel-loader.

Reproduction: https://codesandbox.io/s/ll9184r7mz

I copied your gatsby-node.js file into my project and put linaria/loader before babel-loader, but it throws another error: Error: .inputSourceMap must be a boolean, object, or undefined

Why do we need linaria with gatsbyjs?

Please help me to understand here!

As I know the improvements of Linaria over Styled components or Emotion are

  • Remove CSS generation runtime (small JS bundle)
  • No generation of CSS at runtime (faster page loads)

And Gatsbyjs is static site generator that optimize static assets at build time, so it generate style components CSS at build time.

So the my question is Why we need to use Linaria with gatsbyjs?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • fix(deps): update dependency @linaria/webpack-loader to v4.5.4
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency @linaria/core to v6
  • chore(deps): update dependency @linaria/react to v6
  • chore(deps): update dependency eslint to v9
  • chore(deps): update github/codeql-action action to v3
  • chore(deps): update yarn to v4
  • fix(deps): update dependency @linaria/server to v6
  • fix(deps): update dependency @linaria/webpack-loader to v5
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql.yml
  • actions/checkout v3
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
.github/workflows/main.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
package.json
  • @babel/core ^7.18.10
  • @babel/preset-typescript ^7.18.6
  • @linaria/server ^4.0.0
  • @linaria/webpack-loader ^4.1.2
  • babel-preset-gatsby ^3.0.0
  • @babel/cli ^7.18.10
  • @babel/eslint-parser ^7.11.0
  • @cometjs/eslint-plugin ^2.0.0
  • @linaria/core ^4.1.1
  • @linaria/react ^4.1.2
  • @types/react ^18.0.17
  • @types/react-dom ^18.0.6
  • babel-preset-gatsby-package ^3.0.0
  • eslint ^8.21.0
  • gatsby ^5.0.0
  • react ^18.2.0
  • react-dom ^18.2.0
  • typescript ^5.0.0
  • webpack ^5.74.0
  • @linaria/core ^4.0.0
  • @linaria/react ^4.0.0
  • gatsby ^3.0.0 || ^4.0.0 || ^5.0.0
  • react ^16.8.0 || ^17.0.0 || ^18.0.0
  • react-dom ^16.8.0 || ^17.0.0 || ^18.0.0
  • yarn 3.5.1

  • Check this box to trigger a request for Renovate to run again on this repository

Not working in Gatsby production mode

Environment

node: 8.12.0
gatsby: 2.12.0
gatsby-plugin-linaria: 1.2.0
linaria: 1.3.1
react: 16.8.6

Description

  • I have created a new starter project with Gatsby via the following command:
    npx gatsby new my-default-starter https://github.com/gatsbyjs/gatsby-starter-default

  • Then added the required packages via:
    yarn add gatsby-plugin-linaria linaria

  • After that, I added the gatsby-plugin-linaria plugin at the end of plugins in the gatsby-config.js file.

  • Lastly I edited the components/header.js file to reflect the following:

import { Link } from 'gatsby'
import { styled } from 'linaria/react'
import PropTypes from 'prop-types'
import React from 'react'

const MainHeader = styled.header`
  background: rebeccapurple;
  margin-bottom: 1.45rem;
`

const Header = ({ siteTitle }) => (
  <MainHeader>
    <div
      style={{
        margin: `0 auto`,
        maxWidth: 960,
        padding: `1.45rem 1.0875rem`,
      }}
    >
      <h1 style={{ margin: 0 }}>
        <Link
          to="/"
          style={{
            color: `white`,
            textDecoration: `none`,
          }}
        >
          {siteTitle}
        </Link>
      </h1>
    </div>
  </MainHeader>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

After following these steps, I ran the project in development via npm start and it works flawlessly.

But running in production via npm run build && npm run serve, the build is successful but the styles do not get applied. The class is applied but the styles are not reflected anywhere.

image

I also tried deleting the public, .cache and linaria-cache folders but it didn't make any difference.

Doesn't work with core-js v3

Works fine with v2, will this package be updated in the future to support v3?

detailed error:
success run queries - 6.543s - 236/236 36.07/s

ERROR #98123 WEBPACK

Generating SSR bundle failed

Cannot find module 'core-js/modules/es6.regexp.to-string'

File: .cache\develop-static-entry.js

Using global styles

How can global styles be used in a Gatsby application?

Documentation says that we can add global styles using the following syntax, but it doesn't get applied:

export const globals = css`
  :global() {
    html {
      box-sizing: border-box;
    }

    *,
    *:before,
    *:after {
      box-sizing: inherit;
    }

    @font-face {
      font-family: 'MaterialIcons';
      src: url(../assets/fonts/MaterialIcons.ttf) format('truetype');
    }
  }
`;

Should this be injected by gatsby-plugin somehow? Thank you

Causes infinite refresh loop on Gatsby

These are firing off in an infinite loop:

$ gatsby develop

[....]

ℹ 「wdm」: Compiling...
 DONE  Compiled successfully in 41ms                                                                                                 6:48:14 PM

ℹ 「wdm」:
ℹ 「wdm」: Compiled successfully.
 WAIT  Compiling...                                                                                                                  6:48:14 PM

ℹ 「wdm」: Compiling...
 DONE  Compiled successfully in 38ms                                                                                                 6:48:14 PM

ℹ 「wdm」:
ℹ 「wdm」: Compiled successfully.
 WAIT  Compiling...                                                                                                                  6:48:14 PM

ℹ 「wdm」: Compiling...

Top of the message with DEBUG="*" on:

ℹ 「wdm」: Compiling...
  babel:config:loading:files:plugins Loaded preset '/path/node_modules/linaria/lib/babel/index.js' from '/path/website'. +272ms
  babel program.body[0] ImportDeclaration: enter +282ms
  babel program.body[0] ImportDeclaration: Recursing into... +1ms
  babel program.body[0].specifiers[0] ImportDefaultSpecifier: enter +0ms

I'm using yarn workspaces, could be a version mismatch, though I haven't seen this issue before.

Plugin doesn't work

Hellow!
I have installed Gatsby with Typescript and Linaria with this plugin.
But when i try to start dev mode, application crashes with error:

ERROR #98123  WEBPACK.DEVELOP

Generating development JavaScript bundle failed

/path-to/.cache/fast-refresh-overlay/helpers/focus-trap.js: Cannot read properties of null (reading 'consequent')

File: .cache/fast-refresh-overlay/helpers/focus-trap.js

failed Building development bundle - 5.285s
ERROR in ./.cache/fast-refresh-overlay/helpers/focus-trap.js
Module build failed (from ./node_modules/@linaria/webpack-loader/lib/index.js):
TypeError: /path-to/.cache/fast-refresh-overlay/helpers/focus-trap.js: Cannot read properties of null (reading 'consequent')
...
...

The repository with representation of this bug:
https://github.com/mrKimura/gatby-with-linaria

Temporary workaround

Temporary workaround

gatsby-node.js

const path = require(`path`)
exports.onCreateWebpackConfig = ({actions,getConfig}) => {
	actions.setWebpackConfig({
		resolve: {
			alias: {
				"@reach/router" : path.dirname(require.resolve(`@gatsbyjs/reach-router/package.json`))
			}
		}
	})
}

Originally posted by @tadeas22 in #115 (comment)

npm install issue with Gatsby v4.x.x

Hi, when I try to npm install (npm version: 8.1.2) gatsby-plugin-linaria, with gatsby 4.4.0, the following error occurs:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   gatsby@"4.4.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer gatsby@"^2.0.0 || ^3.0.0" from [email protected]
npm ERR! node_modules/gatsby-plugin-linaria
npm ERR!   gatsby-plugin-linaria@"3.1.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Presumably, #139 was meant to provide this support, but it seems missing the version increment for the version property in package.json? Or perhaps the latest package yet been published to npm registry?

"version": "3.1.0",

Unexpected identifier?

I'm using TypeScript. Linaria is after TypeScript in my config.

./src/components/header.tsx
Module build failed (from ./node_modules/linaria/loader.js):
C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\@reach\router\es\index.js:12
import React from "react";
       ^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:83:7)
    at Module.evaluate (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:200:18)
    at Module.<anonymous> (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:184:13)
    at Module.require (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:134:23)
    at C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\gatsby-link\index.js:24:15
    at Script.runInContext (vm.js:133:20)
    at Module.evaluate (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:203:12)
    at Module.<anonymous> (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:184:13)
    at Module.require (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:134:23)
    at C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\.cache\gatsby-browser-entry.js:69:43
    at Script.runInContext (vm.js:133:20)
    at Module.evaluate (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:203:12)
    at Module.<anonymous> (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:184:13)
    at Module.require (C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\node_modules\linaria\lib\babel\module.js:134:23)
    at C:\Users\deklan\Documents\Code\gatsby-testing\gatsby-site\src\components\header.tsx:3:15
    at Script.runInContext (vm.js:133:20)
import React from 'react';
import { Link } from 'gatsby';
import { styled } from 'linaria/react';

type Props = {
   siteTitle: string;
};

const HeaderContainer = styled.div`
   background: rebeccapurple;
   margin-bottom: 1.45rem;
`;

const NameBlock = styled.div`
   margin: 0 auto;
   max-width: 960;
   padding: 1.45rem 1.0875rem;
`;

const StyledLink = styled(Link)`
   color: white;
   text-decoration: none;
`;

const Heading = styled.h1`
   margin: 0;
`;

const Header: React.FC<Props> = ({ siteTitle }) => (
   <HeaderContainer>
      <NameBlock>
         <Heading>
            <StyledLink to="/">{siteTitle}</StyledLink>
         </Heading>
      </NameBlock>
   </HeaderContainer>
);

export default Header;

Make CSS Extraction an option.

Currently, this plugin does CSS Extraction by default and cannot be disabled by the user at will.

I still recommend enabling this option by default but it should be able to disable if the user wants. (Useful for single pages without code splitting.)

TS: Using the *** tag in runtime is not supported.

I believe this is related to #9.

I have Typescript, with [email protected].
If I use v1.1.1 of this plugin, everything works.
If I update to v1.1.2 I get:

WebpackError: Using the "css" tag in runtime is not supported. Make sure you have set up the Babel plugin correctly.
  
  - css.js:4 css
    [lib]/[linaria]/lib/core/css.js:4:1
...

(in the config I have this plugin listed after the Typescript one, as instructed)

Unexpected token 'export'

Everytime i try to use styled as mentioned here https://github.com/callstack/linaria/blob/master/docs/BASICS.md#styling-custom-components result in SyntaxError

An unexpected runtime error ocurred during dependencies evaluation: 
/..../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js:1
(function (exports) { export default function _objectWithoutPropertiesLoose(source, excluded) {
                      ^^^^^^

SyntaxError: Unexpected token 'export'
    at new Script (vm.js:88:7)

package.json

...
    "linaria": "^2.0.2",
    "gatsby-plugin-linaria": "^2.2.0",
...

This issue callstack/linaria#575 (comment) seems to be similar but last comment says that the error should be fixed

TypeError: filename.endsWith is not a function

Using the extractCritical option:


{
      resolve: 'gatsby-plugin-linaria',
      options: {
        extractCritical: true,
      },
    },

gives me this error when building:

TypeError: filename.endsWith is not a function

  • Gatsby 4
  • Node 16.6.0
  • Linaria 3.0.0-beta.13
  • gatsby-plugin-linaria 3.1.0

File with extracted CSS styles not link to my output html

Hello!
I'm trying this plugin. In production build the styles are being extracted to a file, but the file is not being linked to my document.
Styles in my document was extracted to <head> and look like:

<head>
  <style data-href="/styles.3ca6a414f83d987c3880.css" data-identity="gatsby-global-css">
    .s1sgzzc0 {
      color: 'red';
    }
  </style>
</head>

And so I see that the css file is not being loaded and not being used.
How can I make the resulting css file connect via <link rel="stylesheet"... ?

gatsby-config.ts:
plugins: ['gatsby-plugin-typescript', 'gatsby-plugin-linaria'],

"gatsby": "4.16.0",
"linaria": "2.3.1",

Sorry, English isn't my native language. )

warning 'css' is defined but never used

For each usage of css, I'm getting next warning:
2:10 warning 'css' is defined but never used no-unused-vars

I've tested everything on a plain project:

import React from "react"
import { css } from "linaria"

const style = css`
  background-color: red;
`

function Test(props) {
  return <div className={style}>Styled with css</div>
}

export default Test

This issue is slowing down my hot reload significantly. How can I fix that?

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.