I have a react app and I want to have sass and css support. The problem is when I import the sass or css modules it is not applied to the tags. I mean look at the code below I want the number 2 way of using styles :
import React from 'react';
import PropTypes from 'prop-types';
import style from './index.module.scss';
import { Header, Footer, Container } from '..';
import './style.scss'; // 1. this way is applying
import style from './style.scss'; // 2. this way is not applying
export const Layout = ({ children }) => (
<div className="content"> // 1. this way is applying
<Header />
<Container>
<div className={style.content}> // 2. this way is not applying
{children}
</div>
</Container>
<Footer />
</div>
);
Layout.propTypes = {
children: PropTypes.any.isRequired,
};
export default Layout;
and this is my webpack:
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const cones = require('./cones.json');
module.exports = {
mode: 'development',
entry: './src/index',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CopyWebpackPlugin([{ from: 'public/index.html' }]),
],
devServer: {
port: 3000,
contentBase: path.join(__dirname, './public'),
hot: true,
open: true,
historyApiFallback: true,
before(app) {
app.get('/api/cones', (req, res) => {
res.json(cones);
});
},
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.scss'],
},
};
I think there is something wrong with the style-loader which can not load the styles module in that way.
The "number 2 way" is called CSS Modules. In order to use it you need to turn modules
on in your options for css-loader
. See if this works:
{
test: /\.s[ac]ss$/i,
loader: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
'sass-loader',
],
},