Code Monkey home page Code Monkey logo

react-scoped-styles's Introduction

Scoped Styles for React

NPM

Get your CSS classes scoped by component directory

How it's different from CSS Modules?

In CSS Modules you have to manually import and assign classes

import styles from './button.styl';

const Button = () => (
  <button className={styles.foo}>Press Me</button>
);

React Scoped Styles doesn't require to change the conventional styling workflow. You still assign your classes with plain strings.

import './button.styl';

const Button = () => (
  <button className="foo">Press Me</button>
);

Installation

npm i react-scoped-styles

Usage

The module assumes that component file and its styles are in the same directory. This is sample for Stylus. The same applies for Sass and others.

+-- button
   +-- Button.tsx
   +-- button.styl

Button.tsx

  import React from 'react';
  import './button.styl';

  const Button = () => (
    <button className="foo">Press Me</button>
  );

  export default Button;

button.styl

.foo
    border none
    padding 10px 30px
    color white
    background-color darkslateblue

This will be rendered to

<button class="button-c65bae6565-foo">Press Me</button>
.button-c65bae6565-foo {
  border: none;
  padding: 10px 30px;
  color: #fff;
  background-color: #483d8b;
}

Getting started

The module exposes two loaders both for componenets and styles.
Append the script-loader after it has been transpiled by TypeScript or Babel.
And style-loader should be after the preprocessor loader and before the css-loader.

webpack.config.js

module.exports = {
  module: {
    rules: [
      // TypeScript
      {
        test: /\.tsx?$/,
        use: [
          'react-scoped-styles/script-loader',
          'awesome-typescript-loader'
        ]
      },
      // Babel
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          'react-scoped-styles/script-loader',
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react']
            }
          }
        ]
      },
      // Stylus
      {
        test: /\.styl$/,
        use: [
          'style-loader',
          'css-loader',
          'react-scoped-styles/style-loader',
          'stylus-loader'
        ]
      },
      // Sass
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'react-scoped-styles/style-loader',
          'sass-loader'
        ]
      }
    ]
  }
};

Globals

To use global styles you can pass globalsPrefix options to both loaders and prefix your classes with it.
(app is applied by default)

const scopedStylesOptions = {
  globalsPrefix: 'app'
};


{
  loader: 'react-scoped-styles/script-loader',
  options: scopedStylesOptions
}
// ...
{
  loader: 'react-scoped-styles/style-loader',
  options: scopedStylesOptions
}

Thus classes with app- prefix will be ignored.

const Button = () => (
    <button className="foo app-global-class">Press Me</button>
);
.foo
    border none
    padding 10px 30px
    color white
    background-color darkslateblue

.app-global-class
    background-color purple

Becomes

<button class="button-c65bae6565-foo app-global-class">Press Me</button>
.button-c65bae6565-foo {
  border: none;
  padding: 10px 30px;
  color: #fff;
  background-color: #483d8b;
}
.app-global-class {
  background-color: #800080;
}

Conditional classes

To use conditional classnames you can use the classes function.
Note that the classnames should be inline

import React, { useState } from 'react';
import { classes } from 'react-scoped-styles';
import './sidebar.styl';

export const SideBar = () => {
    const [open, setOpen] = useState(false);

    return (
        <div className={classes([open, 'open'], 'sidebar')}>
            ...
        </div>
    )
};

API

classes (
    ...([boolean, string] | string)[]
) => string;

classes function accepts arrays of [condition, className] pairs, and class-name strings or default classes.

<div className={classes('default', [true, 'applied'], 'another-one', [false, 'not-applied'])} />

All classes should be INLINE, this won't work

const someClass = 'some';
const someCondition = true;

<div className={classes([someCondition, someClass])} />

react-scoped-styles's People

Contributors

constgen avatar gevaghajanyan avatar nairinarinyan 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

Watchers

 avatar  avatar  avatar  avatar  avatar

react-scoped-styles's Issues

If css containes a style without semicolon, building fails

Try to put background image as a last style in a rule but without a semicolon delimiter. This is valid CSS. The last semicolon is optional in the last line of the CSS rule. But this brakes building with react-scoped-styles. The issue doesn't apear if semicolon is always present. Can't be reproduced if the last line doesn't contain url(...) function.

image

image

Seems like an issue with regular expression.

"|" in className breaks compilation

Using vertical line in the slassName breaks compilation as it produces invalid JavaScript code

<div className="test-classname | test" />

I know this is weird. But this is valid HTML and should not fail.

The error is thrown during the build time

ERROR in ./src/images/Image.jsx 47:50
Module parse failed: Unexpected token (47:50)

Actual className

className: "images-ffe673fcf7-test-classname" test"

Expected className

className: "images-ffe673fcf7-test-classname images-ffe673fcf7-test"

How to use vendors css class without getting scoped to component? (ex. Bootstrap)

Hi, i'm trying to configure this plugin in my CRA. It's awesome, so easy to implement.

But i didn't figure out how to use global CSS class from vendor CSS like bootstrap without get this class scoped too.

Maybe the plugin should scope only classes that are present in CSS file and not all classes by default, but i'm not sure that script-loader can read style-loader result.

There is an easy way to do that?

Thanks in advance!

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.