I am trying to make CSS Modules work with React components. My code is as follows:
import styles from './style.css';
const Header = () => {
return (
<header className={styles.main}></header>
)
};
export default Header;
CSS is just
.main { background: red; }
And webpack config:
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var WebpackNotifierPlugin = require('webpack-notifier');
var precss = require('precss');
var autoprefixer = require('autoprefixer');
var path = require('path');
var sassLoaders = [
'css-loader?modules',
'postcss-loader?modules',
'sass-loader?sourceMaps&modules&includePaths[]=' + path.resolve(__dirname, './sass')
];
var config = {
entry: './app/index.js',
output: {
path: 'public',
filename: 'index.js'
},
sassLoader: {
includePaths: path.resolve(__dirname, './sass')
},
plugins: [
new WebpackNotifierPlugin({
title: 'Webpack',
alwaysNotify: true
}),
new ExtractTextPlugin('style.css'),
new BrowserSyncPlugin({
port: 7000,
ui: false,
proxy: 'http://localhost:3000/'
})
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react', 'stage-0']
}
},
{
test: /\.css$/,
loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', sassLoaders.join('!'))
}
]
},
postcss: function() {
return [
precss,
autoprefixer({ browsers: ['last 2 versions'] })
];
}
};
module.exports = config;
The problem occurs when I want to run my code. It's no matter if I include scss
or css
file, I am always getting
[0] SyntaxError: style.css: Unexpected token (1:0)
[0] > 1 | .main {
[0] | ^
[0] 2 | background: red;
[0] 3 | }
What can I do?
CSS Modules are turned on for files ending with the .module.css
extension. So, rename the CSS file from style.css
to style.module.css
and change the path while import on Header React Component.
Like this:
import styles from './style.module.css';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With