Git Product home page Git Product logo

styled-jsx-css-loader's Introduction

styled-jsx/css loader

- ⚠️ THIS PROJECT IS NO LONGER MAINTAINED ⚠️ -

TL;DR: You are encouraged to use the styled-jsx/webpack loader built styled-jsx v3+ (also with Next.js v7+) in instead of styled-jsx/css loader.


styled-jsx/css loader was a loader for webpack that let you import CSS files as a styled-jsx css-tagged template literal.

This was pretty useful back when styled-jsx v2 was in fashion.

In August 2018, styled-jsx v3 was released, coming with its own styled-jsx/webpack loader. This is essentially a full built-in replacement for styled-jsx/css loader. One month later, it was also included in Next.js v7, further reducing the need of an external styled-jsx/css loader.

Usage

Since version 2.0.1, styled-jsx allows styles to be defined in separate JavaScript modules, by tagging with css any template literal that contain CSS.

This loader allows to go one step further and define styles in separate CSS files, which will be loaded as modules exporting the style sheet as a css-tagged template literal.

In practice, you are now able to write:

import styles from './styles.css';

<style jsx>{styles}</style>

Installation

It is assumed that your application already depends on styled-jsx, either directly or through Next.js 4.

The loader is typically added as a dependency (or development dependency) to your application using npm or Yarn.

npm install --save-dev styled-jsx-css-loader

Configuration

The loaded module is intended to be Babel-transformed by styled-jsx.

In order to properly configure this, you will need to define webpack rules for the type of files you want to load (typically, the CSS files of your project and/or external modules).

These rules must:

Basic setup

The simplest way to implement this configuration is to stuff it in a single rule of your webpack configuration file:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              babelrc: false,
              plugins: [
                require.resolve('babel-plugin-transform-es2015-modules-commonjs'),
                require.resolve('styled-jsx/babel'),
              ]
            }
          },
          'styled-jsx-css-loader'
        ]
      }
    ]
  }
};

With this setup, your project must depend on:

Setup with Next.js

If you are using Next.js, there are a few more requirements and caveats.

You must configure webpack to emit loaded files as JavaScript modules in the .next/dist build directory, by using Next.js’ built-in emit-file-loader.

It is easier to use Babel presets exclusively (rather than a mix of presets and plugins) in your project’s configuration. Therefore it is recommended to leverage the next/babel preset that is shipped with Next.js:

  • to transform ES2015 modules, using the modules setting of the babel-preset-env plugin, which is part of the next/babel preset
  • to use styled-jsx using the styled-jsx/babel plugin, which is also part of the next/babel preset

Putting it all together, use the following preset in your project’s .babelrc:

{
  "presets": [
    [
      "next/babel",
      {
        "preset-env": {
          "modules": "commonjs"
        }
      }
    ]
  ]
}

Then, customize Next.js’ webpack rules in your project’s next.config.js file, to use your project’s Babel configuration (and no other) for your CSS files:

module.exports = {
  webpack: (config) => {
    config.module.rules.push(
      {
        test: /\.css$/,
        use: [
          {
            loader: 'emit-file-loader',
            options: {
              name: 'dist/[path][name].[ext].js',
            },
          },
          {
            loader: 'babel-loader',
            options: {
              babelrc: false,
              extends: path.resolve(__dirname, './.babelrc'),
            },
          },
          'styled-jsx-css-loader',
        ],
      }
    );

    return config;
  },
};

With this setup, your project must depend on:

Credits and acknowledgements

This loader was inspired by raw-loader, and Next.js’ with-global-stylesheet example.

Many thanks to styled-jsx author Giuseppe Gurgone.

License

MIT

styled-jsx-css-loader's People

Contributors

coox avatar giuseppeg 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

Watchers

 avatar  avatar

styled-jsx-css-loader's Issues

Flash Of Unstyled Content

Hi there,

I'm using styled-jsx-css-loader on the next.js stack exactly as you suggested in the README, but I'm getting a FOUC when loading a page which is fairly annoying:

gif

The code – shortened to what's relevant (the sass plugin doesnt make a difference):

// .babelrc
{
  "presets": [
    [
      "next/babel",
      {
        "preset-env": { "modules": "commonjs" },
        "styled-jsx": {
          "plugins": [
            "styled-jsx-plugin-sass"
          ]
        }
      }
    ]
  ]
}

// next.config.js
[...]
{
      test: /\.css/,
      use: [
        {
          loader: 'emit-file-loader',
          options: {
            name: 'dist/[path][name].[ext].js',
          },
        },
        {
          loader: 'babel-loader',
          options: {
            babelrc: false,
            extends: path.resolve(__dirname, './.babelrc'),
          },
        },
        "styled-jsx-css-loader",
      ]
}
[...]

// navigation.js
import styles from "./navigation.css";

export default () => {
  return (
    <div>
      <Button href="/">Home</Button>
      <Button href="/about">About</Button>
      <Button route="product" params={{slug: "plant"}}>Plant</Button>
      <Button route="product" params={{slug: "tree"}}>Tree</Button>
      <style jsx>{styles}</style>
    </div>
  );

};

Do you experience something differnt? Or is that an implication of the emit-file-loader and therefore a technical limitation or is there anything that we can do on our end?

Any kind of feedback is appreciated :-)

Cheers,
Tom

Support scss syntax

It would be nice to add support for scss. So that I can import my other scss files. for example:

// style.scss
@import "./variables.scss"
// my component
// ...
import styles from './style.scss'
// ...

External module styles

I can't get this to work with external style imports, e.g.:

import styles from 'some-lib/some-stylesheet.css';

Can't resolve 'styled-jsx/css'

I have a brand new Next.js project set up (v4.1.4) with styled-jsx-css-loader configured in next.config.js exactly as it says in the README here and am trying to import a css file on index.js:

import styles from '../styles/styles.css';

export default () => (
  <div>
    <style jsx>{styles}</style>
  </div>
);

However, getting the following error upon starting next:

Error in styles/styles.css
Module not found: Error: Can't resolve 'styled-jsx/css' in '...'

and the console error:

 ERROR  Failed to compile with 1 errors

This dependency was not found:

* styled-jsx/css in ./styles/styles.css

To install it, you can run: npm install --save styled-jsx/css

What am I doing wrong?

Invalid escape sequence in template

Many thanks for the loader, saved many hours of trials and errors.
Getting this error:

Module build failed: SyntaxError: Invalid escape sequence in template
  1501 | .blockquote-reverse .small:after,
  1502 | blockquote.pull-right .small:after {
> 1503 |   content: '\00A0 \2014';
       |                    ^
  1504 | }

Also, related to escaping issue - icon variables are not rendering correctly, missing backslash when compiled ( i.e. https://github.com/rancher/icons/blob/master/variables.scss )

Prepare for styled-jsx v3

Hi Eric! I will release styled-jsx v3 soon and I wanted to know if you would be interested in adapting this loader to support the new features. You can read about what is changing here vercel/styled-jsx#422

tl;dr basically styled-jsx will produce only scoped styles when you tag the string with css. To get global or (resolved) styles you'd need to tag strings with css.global or css.resolve. I think that we could make your plugin accept an option for the type of compilation to do. The default would be scoped.

The loader should output

const type = options.type === 'global' || options.type === 'resolve' ? `.${options.type}` : '';
"import css from 'styled-jsx/css';\n\nexport default css"+type+"`" + escapedContent + "`;";

Let me know if you are willing to make this change otherwise I'll go ahead and fork :)

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.