So I am trying to avoid having Webpack create the following asset in the build folder used in production:
main.35237d24.css
This configuration works in development. But in production, 'main.35237d24.css' is being generated and a link tag is being created for it. Which is a render blocking resource I am trying to eliminate.
webpack.config.js
{
test: /\.css$/,
use: [
{
loader: "style-loader",
options:{
insert:'head',
injectType: 'singletonStyleTag',
envName: isProduction
},
},
"css-loader"
]
}
What do I need to do here to get the result I'm getting in development, the inlining in the head of the css, for production?
I'd appreciate it.
Thanks,
Ironman
craco provides this recipe for modifying Ant Design LESS variables with create-react-app. However, I don't understand how to modify variables through this config. The variable lessRule in the linked recipe has no visible effect:
const lessRule = {
test: lessExtension,
use: [
{
loader: require.resolve("style-loader"),
},
{
loader: require.resolve("css-loader"),
},
{
loader: require.resolve("less-loader"),
options: {
modifyVars: {
"#primary-color": "#1DA57A",
"#link-color": "#1DA57A",
"#border-radius-base": "2px",
},
javascriptEnabled: true,
},
},
],
};
lessRule is pushed to oneOf but I can't research what this effectively does. What do I do in this config file to see a style change manifested in the app?
craco-antd allows this. I am confused as to what the craco recipe in the question does. I'm not sure it matters.
I really like the separation of className and styleName that babel-plugin-react-css-modules offers for global and local styles respectively, but have had some trouble getting the plugin to work with create-react-app.
I've tried installing the plugin by running
npm install babel-plugin-react-css-modules --save
... as it says to do in the project (github https://github.com/gajus/babel-plugin-react-css-modules#css-modules) ...
... and have also used craco as suggested in a similar thread (#5113) to help overcome the limitations of create-react-app without the need to eject, but am still unable to import a scss file and reference to it using styleName.
Does anyone know if I'm missing something else here? Sorry if it's a noob question, I'm new to React and have been looking for a solution to this for a while now.
1. add the plugin to .babelrc first.
"plugins": [
["babel-plugin-react-css-modules",
{
"webpackHotModuleReloading": true,
"autoResolveMultipleImports": true
}],....
]
2. add css rule in webpack.config.js.
below is my configuration that you can reference from.
make sure that
2.1 option modules set to true.
2.2 localIdentName follow this format. localIdentName: "[path]___[name]__[local]___[hash:base64:5]"
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
options: { cacheDirectory: true }
}
]
},
{
test: /\.css$/i,
use: [
{
loader: ExtractCssChunks.loader,
options: { hot: true }
},
{
loader: "css-loader", //generating unique classname
options: {
importLoaders: 1, // if specifying more loaders
modules: true,
sourceMap: false,
localIdentName: "[path]___[name]__[local]___[hash:base64:5]" //babel-plugin-css-module format
//localIdentName: "[path][name]__[local]" //recommended settings by cssloader#local-scope , this option generate unique classname for compiled css
}
}
]
},
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.
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
}),
},