Coder Social home page Coder Social logo

classnames-loader's Introduction

classnames-loader

npm version

This is a webpack loader that automatically bind css-modules to classnames.

If you are using css-modules, or a similar approach to abstract class "names" and the real className values that are actually output to the DOM, you may want to use the bind variant of classnames module.

Check out this example that shows the difference between classNames, classNames/bind and classnames-loader

Installation

npm install --save-dev classnames-loader

Usage

To enable this loader add classnames before style loader in webpack config:

{
  test: /\.css$/,
  loader: 'classnames!style!css')
}

If you're using ExtractTextPlugin your webpack config should look like this:

{
  test: /\.css$/,
  loaders: ['classnames', ExtractTextPlugin.extract('style', 'css')])
}

Example usage in component:

import { Component } from 'react';
import cx from './submit-button.css';

export default class SubmitButton extends Component {
  render () {
    let text = this.props.store.submissionInProgress ? 'Processing...' : 'Submit';
    let className = cx({
      base: true,
      inProgress: this.props.store.submissionInProgress,
      error: this.props.store.errorOccurred,
      disabled: !this.props.form.valid,
    });
    return <button className={className}>{text}</button>;
  } 
}

You can also access the class names just as you would do that with css-modules:

import { Component } from 'react';
import styles from './submit-button.css';

export default class SubmitButton extends Component {
  render () {
    let text = this.props.store.submissionInProgress ? 'Processing...' : 'Submit';
    return <button className={styles.submitButton}>{text}</button>;
  } 
}

Thanks

@JedWatson for classnames module

License

MIT

classnames-loader's People

Contributors

olegstepura avatar otakustay avatar padcom avatar r3nya 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

classnames-loader's Issues

Extend the loader with default module behavior

In the current version the only way you can interact with the loaded stylesheet is basically to call it as a function. The default way, however, is to get the styles as fields.

It'd be great if we could merge the two approaches into one so that migration from regular styles to classNames is more seamless.

See the following for example implementation and usage:
https://github.com/padcom/react-example-02/blob/master/src/build/classnames-loader.js
https://github.com/padcom/react-example-02/blob/master/src/main/components/Input.js

So basically the imported variable is both an object and a function you can call.

Hot module reloading

I forked the loader to customize it for our codebase and to add HMR and thought you might find it useful:

module.exports.pitch = function(remainingRequest) {
    this.cacheable()

    var cnames = loaderUtils.stringifyRequest(this, "!" + require.resolve("classnames/bind"))
    var styles = loaderUtils.stringifyRequest(this, "!!" + remainingRequest)

    return `
      if (module.hot) {
        var styles = require(${ styles })
        var classnames = require(${ cnames }).bind(styles)

        var fn = function() {
          return classnames.apply(null, arguments)
        }

        // Allow using this as an ES6 module
        fn.default = fn

        // Allow access to the raw style map
        fn.styles = styles

        module.exports = fn

        module.hot.accept(${ styles }, function() {
          fn.styles = styles = require(${ styles })
          classnames = require(${ cnames }).bind(styles)
        })
      } else {
        module.exports = require(${ cnames }).bind(require(${ styles }))
      }
    `;
}

Example with postcss/sass?

Hey I'm trying to setup new config with webpack 2 and not sure how to get this working

Currently have what looks like following

  loaders: [{
    test: /\.scss$/,
    exclude: /(node_modules)/,
    loaders: [
      ExtractTextPlugin.extract('style'),
      'classnames',
      'css',
      'postcss',
      'sass'
    ]
  }, {
    test: /\.(js|jsx)$/,
    exclude: /(node_modules)/,
    loaders: [
      'babel-loader'
    ]
  },
  ],
},

But get an error like this
Module build failed: TypeError: text.forEach is not a function

Any ideas? thanks!

Support a strict mode

It would be nice if this module was able to throw an error if you try to use a css class that does not exists. This should of cause be an optional mode, by providing a query parameter:

{
  test: /\.css$/,
  loaders: ['classnames?strict', ExtractTextPlugin.extract('style', 'css')])
}

If you think this is a viable feature, I'll be happy to create a PR for it.

Kind regards
Sune

Usage along with Jest

I'm using successfully classnames-loader in my project but actually I've a problem when using it along with Jest, as I'm not able to run the loader on the files to test when I load them, and so the function statement breaks:

const styles = require('./styles.scss');

<div className={styles({
        classA: true,
        classB: true
      })}
      >Hi!</div>

something like this breaks because styles is not a classnames-loader function.

To mock .css files in Jest I used identity-obj-proxy:

{
  "jest": {
    "moduleNameMapper": {
      "\\.(css|less)$": "identity-obj-proxy"
    }
  }
}

this works fine when I use the styles object properties directly because mocks all the css classes into a single object, but of course it fails when is used as a function.

How I can configure Jest to run classnames-loader on the files that I need to test?

Cannot find module 'classnames/bind'

Hi!

I setup a repository with the issue https://github.com/jeremybarbet/next-classnames-loader-issue

Steps:

  • create-next-app next-classnames-loader-issue

  • yarn add @zeit/next-sass classnames-loader node-sass -ED

  • Changing next.config.js

const withSass = require('@zeit/next-sass')

module.exports = withSass({
  cssModules: true,
  webpack(config) {
    const classNamesLoader = require.resolve('classnames-loader');
    const styleRules = config.module.rules.filter(rule => rule.test.test('file.scss') || rule.test.test('file.sass'));

    styleRules.forEach(styleRule => {
      if (styleRule.use && styleRule.use.indexOf(classNamesLoader) === -1) {
        styleRule.use.splice(0, 0, classNamesLoader);
      }
    });

    return config;
  },
});
  • Moving index route to a home folder and creating a div using classname

  • Result to:

./pages/home/Home.scss
Error: Cannot find module 'classnames/bind'
ModuleBuildError: Module build failed (from ./node_modules/classnames-loader/index.js):
Error: Cannot find module 'classnames/bind'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:603:15)
    at Function.resolve (internal/modules/cjs/helpers.js:30:19)
    at Object.module.exports.pitch (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/classnames-loader/index.js:11:85)
    at runLoaders (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/NormalModule.js:301:20)
    at /Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:367:11
    at /Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:182:20
    at runSyncOrAsync (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:143:3)
    at /Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:178:3
    at loadLoader (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/loadLoader.js:47:3)
    at iteratePitchingLoaders (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
    at runLoaders (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/loader-runner/lib/LoaderRunner.js:365:2)
    at NormalModule.doBuild (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/NormalModule.js:280:3)
    at NormalModule.build (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/NormalModule.js:427:15)
    at Compilation.buildModule (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/Compilation.js:635:10)
    at factory.create (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/Compilation.js:884:14)
    at factory (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/NormalModuleFactory.js:405:6)
    at hooks.afterResolve.callAsync (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/webpack/lib/NormalModuleFactory.js:155:13)
    at _fn0 (eval at create (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/tapable/lib/HookCodeFactory.js:32:10), <anonymous>:14:1)
    at fileExistsWithCase (/Users/jeremy/Perso/next-classnames-loader-issue/node_modules/case-sensitive-paths-webpack-plugin/index.js:160:11)

Critical severity vulnerabilities

Hello,
I just wanted to update our code base and got an critical severity vulnerabilities error. This is due to the old loader-utils version used in this package.
Please update the packages in order to close this vulnerability.

# npm audit report

loader-utils  <1.4.1
Severity: critical
Prototype pollution in webpack loader-utils - https://github.com/advisories/GHSA-76p3-8jx3-jpfq
No fix available
node_modules/classnames-loader/node_modules/loader-utils
  classnames-loader  *
  Depends on vulnerable versions of loader-utils
  node_modules/classnames-loader

2 critical severity vulnerabilities

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.