Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reccomended way to require CSS in webpack? #176

Closed
drobtravels opened this issue May 7, 2015 · 35 comments
Closed

Reccomended way to require CSS in webpack? #176

drobtravels opened this issue May 7, 2015 · 35 comments

Comments

@drobtravels
Copy link

What is the recommended way to bring in the CSS from this packaged in webpack?

Just doing require('react-select') appears to only bring in the javascript. I was able to get it working by adding require('react-select/less/default.less') or require('react-select/dist/default.css') to my javascript file.

I'm new to node packages so I'm not clear if that is by design or not.

@barsukov
Copy link

I use the same way...

@evandegr
Copy link

@droberts84 can you show your webpack config

@drobtravels
Copy link
Author

See below. Is require('react-select/dist/default.css') not necessary? I looked at package.json and the JS files it references, and didn't see any references to the CSS.

var path = require('path');
var webpack = require('webpack');
var rootPath = path.join(__dirname, '../', '../');

var config = module.exports = {
  // the base path which will be used to resolve entry points
  context: path.join(rootPath, 'frontend'),
  // the main entry point for our application's frontend JS
  entry: './javascripts/bootstrap-app',
};

config.output = {
  // this is our app/assets/javascripts directory, which is part of the Sprockets pipeline
  path: path.join(rootPath, 'app', 'assets', 'javascripts'),
  // the filename of the compiled bundle, e.g. app/assets/javascripts/bundle.js
  filename: 'bundle.js',
  // if the webpack code-splitting feature is enabled, this is the path it'll use to download bundles
  publicPath: '/assets',
  // this all related to source maps
  devtoolModuleFilenameTemplate: '[resourcePath]',
  devtoolFallbackModuleFilenameTemplate: '[resourcePath]?[hash]',
};

config.resolve = {
  // tell webpack which extensions to auto search when it resolves modules. With this,
  // you'll be able to do `require('./utils')` instead of `require('./utils.js')`
  extensions: ['', '.js', '.coffee', '.js.coffee', '.jsx'],
  root: rootPath,
  modulesDirectories: ['node_modules'],
  alias: {
    app: path.join(rootPath, 'frontend', 'javascripts'),
    components: path.join(rootPath, 'frontend', 'javascripts', 'components'),
    flux: path.join(rootPath, 'frontend', 'javascripts', 'flux'),
  }
};

config.resolveLoader = {
  root: path.join(rootPath, "node_modules")
};

config.plugins = [

];

// use jQuery from the rails gem
config.externals = {
  jquery: 'var jQuery'
};

config.module = {
  loaders: [
    { test: /\.coffee$/, loader: 'coffee-loader' },
    { test: /\.es6$/, loader: 'babel-loader' },
    { test: /\.jsx$/, loader: 'babel-loader'},
    // handle stylesheets required from node packages
    { test: /\.css$/, loader: 'style-loader!css-loader'},
    // need to load all react-infinte modules via babel since it contains es6
    { test: /\.js$/, include: path.join(rootPath, 'node_modules', 'react-infinite'), loader: 'babel-loader' },
    // expose flux instance globally as $flux... must use coffe-loader if coffee-script
    { test: path.join(rootPath, 'frontend', 'javascripts', 'flux'), loader: 'expose?$flux!coffee-loader'},
  ],
};

@GabeMedrash
Copy link

This should really be included in the documentation.

@Agamennon
Copy link

my less-loader is failing @import my config has

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

how exactly should we import this with webpack?

@GuruM
Copy link

GuruM commented Sep 25, 2015

+1 styles not appearing for me without manual require as well

@ptim
Copy link

ptim commented Oct 2, 2015

👍 thanks for the tip @droberts84

@sample-usr
Copy link

Still no proper way to require the CSS. @JedWatson should we separate the CSS entirely and leave it to the user however they want to style it?

@tsheaff
Copy link

tsheaff commented Nov 5, 2015

I agree that this is not clear from the documentation and should be more explicit.

@NeXTs
Copy link

NeXTs commented Nov 19, 2015

+1
Had to look for issues to figure out best practices of including CSS, that's how I ended up here. Not obvious.

@jonpincus
Copy link

+1. Not a great initial experience!

@seeya
Copy link

seeya commented Dec 27, 2015

I'm using webpack too and I tried doing import 'react-select/scss/default.scss'; however the styles are not getting loaded. Am I missing something?

@felipeleusin
Copy link

For me it fixed doing import 'style!react-select/scss/default.scss'

@josephtactica
Copy link

This one worked for me:
require('style!css!sass!react-select/scss/default.scss');

@ttyao
Copy link

ttyao commented Feb 3, 2016

I'm also having the styling issue. Is there an official way to resolve this? It would be greatly appreciated if the styling is mentioned in readme.

@christhomas
Copy link

Me too, it would be nice if this was documented, I Thought I'd missed a step, so I guess I'll manually include the file like above.

@aarkerio
Copy link

This way worked for me:
require('react-select/less/default.less')
my webpack file has:
{ test: /\.less$/, loader: 'style!css!less' },

@xie-qianyue
Copy link

In 1.0.0, the require should be require('react-select/dist/react-select.css').

@conor909
Copy link

conor909 commented Apr 26, 2016

If it's not in node_modules and you've installed it with JSPM? @import "react-select/scss/default.scss" doesn't work for me, I also tried putting <link rel="stylesheet" type="text/css" href="jspm_packages/npm/react-select@1.0.0-beta12/scss/select.scss" /> in my index.html, but it doesnt work either. This really should be documented

@markmur
Copy link

markmur commented May 19, 2016

import 'react-select/scss/default.scss'; worked for me with this in my webpack config file:

{
    test: /\.scss$/,
    loader: 'style!css!sass?outputStyle=expanded',
}

@rahulkag
Copy link

rahulkag commented Sep 21, 2016

I am using the scss into my project.
I have added css like import 'style!react-select/scss/default.scss'; but it is not working because element is loading into DOM as show into below image like without any post fix. And since we are using the scss so the classes will appear like 'default_Select_EZy86IIj_D6Msr78 '. there is no chance to apply on element.
image

But when I import css using the href="https://npmcdn.com/react-select/dist/react-select.css" then it is working fine. But in this case we are bypass the scss compile.

Can any one share an idea how we use this using the scss.

Thanks
Rahul

@BotaniQue
Copy link

@rahulkag
+1
Is there a way to use react-select with CSS Modules, so we don't need to move its CSS to globals?

@rahulkag
Copy link

I think component can be write that way where it will take one root selector and the rest of selector will followed by root in side it. And root selector need to apply while calling it.
So that way any component can be work with sass/less or css.

Thanks
Rahul

@ismay
Copy link

ismay commented Oct 20, 2016

I might be mistaken, but since most people seem to use es6 imports with webpack, I'd say that:

// only the css
import { styles } from 'react-select';
// both js and css
import Select, { styles } from 'react-select';

Would be a user-friendly way to import the css.

@bbthorntz
Copy link

bbthorntz commented Oct 28, 2016

Not sure if it helps someone, but I used a small wrapper component for react-select which imports the dependencies. The .jsx file wraps the default <Select /> component in a wrapper class which can be created by css modules.

// Select.jsx (ES6)
import React from 'react';
import ReactSelect from 'react-select';
import styles from './Select.scss';

const Select = (props) => {
    return (
        <div className={styles.wrap}><ReactSelect {...props} /></div>
    )
};

Select.propTypes = {};
Select.defaultProps = {};

export default Select;

The .scss file first runs through the sass-loader and then css-loader (with modules). This allows sass variable configuration and helps namespace the default styles to avoid impacting anything else.

// Select.scss (SASS + CSS Modules)
.wrap {
    :global {
        @import "node_modules/react-select/scss/default.scss";
    }
}

@qburst-hrishikesh
Copy link

Hi,
I am trying to use webpack for bundling my angular1 project. But when I try to use external libraries like bootstrap, angular-bootstrap-calendar etc.. webpack only considers the js ignoring completely the css associated with each library .Now I am forced to import styles from the node-modules which I guess is not the correct way to do it. Is there any proper way to do this?

@lpan
Copy link

lpan commented Feb 2, 2017

@bbthorntz I think it is better to mess with webpack config than adding a wrapper component.

Here is my solution to this problem

module: {
    rules: [
      {
        test: /(\.global\.css$|react-select.css)/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
          },
        ],
      },
      {
        test: /^((?!\.global|react-select).)*\.css$/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              importLoaders: 1,
              sourceMap: true,
            },
          },
    ],
  },

@bbthorntz
Copy link

@lpan this works too. I'd like to think that the React Component + CSS Modules approach I described stops third-party plugins from adding global styles which might conflict with each other though.

@dobromir-bogatev
Copy link

You can do @import "path/to/your/css" inside <style> tag. If you want it to be accessed to all your pages, include it to your outer-most layer.

@jeghers
Copy link

jeghers commented Jun 9, 2017

Sorry guys I am not quite getting the context of how to fix this. I am using 'react-cool-starter' as my starter kit and it does not have an index.html. Also it uses PostCSS which complicates things.

I understand that I need something like...

require('style!css!sass!react-select/scss/default.scss');

...but I am not sure where it goes. Can someone please clarify what file it goes in and post an example of that file so I can see how the command is placed?

@pinhassi
Copy link

pinhassi commented Jun 28, 2017

Working with webpack and mocha / chai:

css failed on chai test:
import 'style!css!less!react-select/dist/react-select.min.css'

I used less instead:
require('react-select/less/default.less')

In webpack.config file:
{ test: /.less$/, loader: 'style!css!less' }

@jsj14
Copy link

jsj14 commented Jul 17, 2017

@felipeleusin Thanks!
I just had to add style-loader instead. import 'style-loader!react-select/scss/default.scss'

@agirton
Copy link
Collaborator

agirton commented Jul 17, 2017

Since this question has been answered quite a bit in here. Going to close this out.

@speedy250
Copy link

speedy250 commented Apr 6, 2018

Nothing here really solved my problem of importing the styles - and the repeated request to have some process included in the documentation was not addressed either so I don't think this is sufficiently answered to close.

If anyone is using css-loader with localIdentName to prevent naming conflicts, and running into the same issue of the style names being transformed but the component style-names remaining unchanged (which I believe stemmed from using Typescript, and my node_modules/**/*.js files not going through a loader) I added this loader to my webpack.config to quick fix the problem:

{
  test: /(\.css)$/,
  resourceQuery: /^\?raw$/,
  use: ExtractTextPlugin.extract(Object.assign({
    fallback: 'style-loader',
    use: ['css-loader', 'postcss-loader']
  }))
},

Then loading the styles in the appropriate .tsx file with require('react-select/dist/react-select.css?raw')

@JedWatson
Copy link
Owner

@shudson250 the problem is that how to import the styles is highly dependent on each setup, and there is no "one size fits all" solution. If somebody wants to try their hand at improving the documentation with a PR, I'd be happy to review it - possibly even a link to this issue for suggestions if somebody is having trouble.

But anything much more specific than directing users to either import the css|less|scss if they're using webpack, or include the stylesheet with a <link> tag, is really documenting how to use webpack and various loaders, which I don't believe is within the scope of react-select's docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests