Configuring CSS modules in development/production with webpack and React - reactjs

How can use CSS modules in production and load standard css file in production?
I am configuring an new application with React using webpack
In development I use CSS modules using webpack loaders :
into my .jsx file I import the style file:
import style from './stile.scss';
export class App extends React.Component {
render() {
return (
<div>
<div>
<span className={style.title}>Ciao</span>
</div>
</div>
)
}
}
then I use the following webpack configuration for loaders for my stylesheets:
loaders: [
{
test: /\.(scss|css)$/,
loader: 'style-loader!css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap'
}
]
this way everything works (the style is included in the .js file and classes properly hased)
but in production? I should leave the browser render all the classes included in the webpack bundle.js output file?
I would rather create a css file with webpack (and ExtracttextPlugin) with all my style:
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('css-loader' )
}
and link the .css produced in my index.html
Problem is that now all my classes definitions into the React components are no longer rendered in the browser.
How should I solve this?

You can't just switch from using CSS modules to not using them, that doesn't work out as your code depends on it. Also there is no reason not to use CSS modules in production as well. What you want to change is not the CSS modules, but the way you include the CSS. Instead of having it in your JavaScript bundle you can extract them with extract-text-webpack-plugin into a separate .css file, but you still need to use the same configuration for the loaders.
webpack 1
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap')
}
The first argument style-loader is only used as a fallback if the CSS can't be extracted.
webpack 2
The arguments to ExtractTextPlugin.extract changed and for readability using options instead of an inline query in the string.
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
localIdentName: '[name]-[local]___[hash:base64:5]'
}
},
{ loader: 'sass-loader', options: { sourceMap: true } }
]
})
}

Related

Make babel resolve urls in jsx file like css-loader does it with css files

I am using webpack plugin ImageMinimizerWebpackPlugin which minimizes and generates images. When i add this to my css files:
.demo {
background: url("..//public/logo.png?as=avif");
}
It will generate new Avif image. But when I do this:
export default function Component() {
return <img src="../public/logo.png?as=avif" />;
}
It would not resolve the src url. I figured out that it is because there is no loader configured to do this.
Here is my babel loader configuration:
{
test: /\.[jt]sx?$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react",
]
},
},
}
Is there any babel plugin or webpack loader which does this?
I tried to search the web of such loader but I did not find any.

webpack: SASS loader fails "Module build failed (from ./node_modules/sass-loader/lib/loader.js)"

I've been trying to use sass-loader on webpack v4, but it fails to load scss files in a React component with TypeScript.
Here is a simplified snippet of the code.
//index.tsx
import * as React from 'react';
import './styles.scss';
const Navigation = () => {
return (<div className="app-bar"></div>)
}
//styles.scss
.app-bar {
background-color: #2196f3;
}
The following code is from my webpack config.
module: {
rules: [
//loaders for jsx, tsx etc
{
test: /\.(css|scss)$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
},
{ loader: 'sass-loader' }
]
}]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new CleanWebpackPlugin(),
]
I followed the official doc's example, but it fails to load the styles.scss.
Just in case, I re-installed style-loader, css-loader, sass-loader (and node-sass), but it didn't solve the error.
The error message is ...
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
I'm running webpack via Laravel Mix, but don't know if Laravel has anything to do with it.
What caused this issue? Any advice will be appreciated.
You dont need to put css in the test section because the sass-loader and css-loader will take care for you and it will transform your scss to css file
Below is my config
{
test: /\.scss$/,
use: [
//'style-loader' was the culprit, so I just needed to remove it
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
I seem to remember having the same issues with webpack. I switched from SASS to Styled Components, it's a css-in-js library. I was wary at first but it's great.
https://www.styled-components.com/
It allows you to change CSS styles programmatically using React props. For example if I want to change the opacity of a menu when a button is clicked I can do it like this:
opacity: ${props => (props.menuOpen ? 1 : 0)};
That’s just one benefit, check the docs to see others. I find using React with styled-components is a great way to work. You have your JS, CSS and HTML all being generated in one place.

React : CSS class name import not working

i have a <main> div in my react component and im importing some class name from a class css file, but the class name is not getting integrated to the main div when i try to inspect it in the browser. when i simply use other class names its working like <main className="test"> but importing classes is not working.
This is my component :
import React from 'react';
import Aux from '../../hoc/Aux';
import classes from './Layout.css';
const layout = (props) => (
<Aux>
<div>
Test paragraph
</div>
<main className={classes.Content}>
{props.children}
</main>
</Aux>
);
export default layout;
This is my css
.Content{
color: red;
margin-top: 20px;
}
I did npm run eject command after creation, if there is something to do with the webpack configuration file please help me
( i haven't made any changes there after eject command )
Here is the css part of webpack dev config file
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
import './Layout.css';
Then use it like a normal CSS
<main className="Content">
You can also use your classes as objects with this format:
In your CSS file:
Wrap your classes and id's with :local(.className)
Example
:local(.Content) { width: 100px; }
In your React Component:
import classes from './stylesheet.css'
<div className={classes.Content}></div>
Actually I've used it like this:
import classes from './Layout.module.css';
As you see in the text of your question:
// using the extension .module.css
You have to configure some staff. follow these steps:
npm run eject run this command inside your project root directory
search cssRegex and add the following lines under use: getStyleLoaders({
modules:true,
localIdentName:'[name]__[local]__[hash:base64:5]'
Enjoy!
Make sure 'npm run eject' run successfully then you can access webpack.config.js file in config folder.
Stop the server.
Go to webpack.config.js
Find cssRegex and update as given in the image
Restart the server
If you're using Windows, don't name file 'Aux' it's reserved name.
Solution is just to name your CSS files as (in your case) Layout.module.css and then import them as such.
You don't need to eject as from the Create React App 2.0 since it uses CSS Modules out of the box.
Don't you need to specify the file's extension like import classes from './layout.css';?
Try to instal style-loader and css-loader packages. Then add to you webpack this:
{
test: /\.css$/,
loaders: [
'style-loader?sourceMap',
'css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
}
I got if from css-modules documentation and I hope it will help you to achieve what you need.
None of the above solutions worked for me, if you're using a react version with react-scripts#2.0.0 and higher, they probably wouldn't work for you either.
you must used the CSS Modules alongside regular stylesheets using the [name].module.css file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]_[classname]__[hash].
example Header.module.css
nb: header here can be any name
To use class names like an object you need to do 2 things:
Write import like import * as classes from './Layout.css';
Include typings defenition for your style.
Example for Typescript - create Layout.css.d.ts file with export const Content: string;
Be sure that you define camelCase option for css-loader to resolve dash-classes into camel-case properties that you define in Layout.css.d.ts.
I was also working on a react tutorial and faced same issue.
I updated my webpack.config.js file at line 420 and it was working for me then. Please try it out.
line 420:
localIdentName:'[name][local][hash:base64:5]',
For latest version no need to set
localIdentName: '[name][local][hash:base64:5]', // no need set any where
Just give your css name with postfix like FileName.module.css ex Personal.module.css
Then class name like below filename_classname_randomstring
Personal_Person__3L9tz
it working for me
this works for me
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
the other answers not worked for me
so I used this solution and worked fine
1: run the npm run eject command
2: go to config/webpack.config.js and search for cssRegex
3: use this code in that particular section
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules:{
localIdentName:'[name]__[local]__[hash:base64:5]'
},
}),
Just add the below configuration to config/webpack.config.js after running npm run eject in the command line in the project folder and select yes when propted
I have noticed many reference to test: cssRegex block, though you may not have it in the webpack config.
If the above is your case try to open webpack.config.dev.js and find block starting with test: /\.css$/, (row 160 in my case). Then add the following lines so final result looks like this:
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
},
},
This should enable css modules to work.
Here is the solution:
yarn run eject
Go to the config/webpack.config.js
Update the file as the screenshot.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
localIdentName:'[name]__[local]__[hash:base64:5]',
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent
}),
},

webpack css loader exclude css files

Currently, I have multiple css files under some react components. Those css files are required conditionally. However, css loader and extract text plugin include all the css files which is not required in a js file. Is there any way to exclude files by regex using test config or other way?
test: /\.css$/,
lets say I have css files
bear.css
cat.css
styles.css
colors.css
... multiptle different css files
I edit the regex correctly but still it include all css no matter what which i tested by leaving one comment on css file which should not be included on bundle.css
This is how I require css file
const css = require(`./styles/${config}`)
I will answer myself. Webpack's include exclude used to determine the file need to be transpile or not, which is nothing to do with excluding files from your bundle. For example, you add regex to exclude, it will still be in your bundle. However, it will not be processed or transpiled(depends on your loader you use).
Therefore, you should use something likeignore loader to remove from your bundle.
According to webpack documentation you can include style-loader and css-loader in your webpack.config.js file:
config = {
entry: "./app/Main.js",
output: {
publicPath: "/",
path: path.resolve(__dirname, "app"),
filename: "bundled.js"
},
mode: "development",
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-react", ["#babel/preset-env", { targets: { node: "12" } }]]
}
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
]
}
}
After that you could add css directly in your Main.js file
import Example from 'Example';
import './css/bear.css';
import './css/cat.css';
...

react-toolbox css config in webpack 2 not working

I am working with webpack and I have been trying to config react-toolbox library.
I managed to make it work but the css is not loading.
webpack.config.js
You haven't configured your style loader to emit CSS modules
Add this to your style loader
loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
This will turn on CSS modules, and also set it up for allowing postCSS to hook up to it
Remember that this will now treat any .scss or .css file as a locally scoped module, so if you have any separate normal SCSS or CSS that you want to remain global, you will need to add another rule for them
// EDIT
It may be confused using the loader string if your other loader configs are still in that array (as the above string is shorthand to combine them all), try instead separately using config objects...
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
localIdentName: '[name]__[local]___[hash:base64:5]',
modules: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
postcssNext
]
}
}
]
}
React Toolbox no longer uses SCSS having migrated to PostCSS so I've left that out - if you use it then add that in the same manner

Resources