Webpacker: Importing styles in a JavaScript file does not appear to work

Created on 3 Apr 2018  路  4Comments  路  Source: rails/webpacker

Rails: 5.1.4
Node: 9.5.0
Webpacker: 3.4.3
Webpack: 3.10.0

I'm using the React example (app/javascript/packs/hello_react.jsx). In it, I've imported a stylesheet and added a class to the hello div:

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";
import "../styles/hello_react.css";

const Hello = props => <div className="hello">Hello {props.name}!</div>;

Hello.defaultProps = {
  name: "David"
};

Hello.propTypes = {
  name: PropTypes.string
};

document.addEventListener("DOMContentLoaded", () => {
  ReactDOM.render(
    <Hello name="React" />,
    document.body.appendChild(document.createElement("div"))
  );
});

The stylesheet (app/javascript/styles/hello_react.css) has:

.hello {
  background: #ff0000;
  font-size: 20px;
  color: #fff;
}

However, this doesn't appear to have any effect. The component renders to the screen without any styles.

Most helpful comment

Are you using dev server or watcher? You would need to add a stylesheet_pack_tag along with javascript_pack_tag in the view with same pack name to include styles.

All 4 comments

Are you using dev server or watcher? You would need to add a stylesheet_pack_tag along with javascript_pack_tag in the view with same pack name to include styles.

@gauravtiwari Thank you for the quick response! I really appreciate it.

I see. So when you have a JavaScript pack, like hello_react.jsx and you use a CSS import in it (or in some JS file getting used by it), a CSS pack with the imported styles is automatically generated, having the same name as the JS pack. If I add the stylesheet_pack_tag('hello_react') to my Rails view, my imported JS styles work.

Thank you for the link. I read that page a couple of times, but didn't quite grok it until now.

@elliotlarson Yep, you got it 100% right 馃憤

(or in some JS file getting used by it)

Nope, not all files - just JS files inside packs/ folder or any JS file that are imported in packs/*.js file and is importing CSS asset. Does that make sense?

If you have CSS asset imported in a pack file or any file that's imported inside packs then you will get a separate CSS file, same name as pack name to link in your view (except in HMR mode with webpack dev server). In HMR mode CSS is included directly inside JS file for hot reloading i.e. magically load changes without browser refresh - https://webpack.js.org/concepts/hot-module-replacement/.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ankitrg picture ankitrg  路  3Comments

inopinatus picture inopinatus  路  3Comments

pioz picture pioz  路  3Comments

johan-smits picture johan-smits  路  3Comments

ilrock picture ilrock  路  3Comments