Skip to content

bootstarted/css-js-loader

Repository files navigation

css-js-loader

Write your styles with in JavsScript.

build status coverage license version downloads

Usage

Install:

npm install css-js-loader value-loader

Add to your webpack.config.js:

module.exports = {
  ...
  module: {
    loaders: [{
      test: /\.css(\.js)?$/,
      loaders: ['style-loader', 'css-loader'],
    }, {
      test: /\.css\.js$/,
      loaders: ['css-js-loader', 'value-loader'],
    }],
  },
};

NOTE: You don't need to chain with value-loader per-se, but doing so gives you caching, nested dependency monitoring/reloading and the ability to use webpack's tree-shaking abilities.

Writing JS Styles

css-js-loader converts JS modules to CSS markup at runtime.

A .css.js file:

export default {
 '.blueText': {
    color: 'blue',
    fontSize: 12,
  },
};

Yields:

.blueText {
  color: blue;
  font-size: 12px;
}

CSS classes can be defined as ES6 named exports.

export const blueText = { ... };

export const greenText = { ... };

export default {
  '.redText': { ... },
};

Is equivalent to:

export default {
  '.blueText': { ... },
  '.greenText': { ... },
  '.redText' { ... },
};

CSS Modules

css-js-loader works great with CSS Modules. Named class exports map directly to the class names that are imported in your component files.

Style file:

export const base = { ... };
export const inner = { ... };

Component file:

import React from 'react';
import {base, inner} from './component.css.js';
export default () =>
  <div className={base}>
    <div className={inner}>
      ...
    </div>
  </div>;