How to give classes in CSS modules better names? - css

I have this config in webpack.config.js:
{
test: /\.css$/,
use: [
{loader: "style-loader"},
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
sourceMap: true
}
}
]
}
It works as expected, but the one small thing can be improved - names of classes generated.
Is it possible to, say, add the generated string to the existing class name?
Like this:
// before:
gSJW8QAdF0l_JiFWFeyjq
// after:
loginContainer_gSJW8QAdF0l_JiFWFeyjq

Refer to the official docs and look for the section about localIdentName and getLocalIdent. Using that you can completely customize your class name. Cheers!

Related

pseudo-selector :host not "compiled"

I am currently migrating an AngularJs project (v1.7.5) to Angular7.
I followed the migration instructions and everything is going pretty well.
Everything?
No, because a small problem resists over and over again.
Since I come from the AngularJs world I don't use AngularCLI and had to write my Webpack configuration by hand.
My problem:
When I try to use the pseudo-selector ":host" in my css files, it is not transformed into "_ngSomething" in my generated output (I use the ViewEncapsulation.Emulated mode).
My question:
Which module (component/loader) is in charge of transforming this pseudo-selector, and how to configure it?
I tried an "ng eject" to extract the webpack config from a project based on angularCLI, but this command seems inaccessible for the moment
Here is my current css section in webpack.conf file
{
test: /\.css$/,
use: [
"exports-loader?module.exports.toString()",
{ loader: "style-loader" },
{ loader: "css-loader", options: { importLoaders: 1 } },
{ loader: "postcss-loader" },
]
}
Thx for any help

Mini-css-extract-plugin - how grap the hash naming on index.html

I try currently to implement mini-css-extract-plugin.
I fail to implement hash naming, when I use it I don't know how lead my index.html file to grap the specific name on the fly.
If someone has any idea would be great.Thanks
Here my webpack.config.js :
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'styles.[contenthash].css'
})
],
module: {
rules: [ {
test: /\.js|jsx$/,
exclude: /node_modules/,
include: path.resolve(__dirname, "src"),
use: [
{
loader: "babel-loader",
options: {
presets: ["es2015", "stage-1", "react"]
}
}
]
},
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "./public"
}
}, {
loader: "css-loader"
}]
}
]},
here my index.html:
<link rel="stylesheet" href="styles.css">
how translate in my html the "[contenthash]" part of my css filename ?
You can use html-webpack-plugin in order to inject the css at build time, it supports costume the hash naming and allows you to provide your own template.
Here my basic understanding of html-webpack-plugin (thereafter HWP).
Seems that HWP create a kind of meta-bundle in which all bundles are merged.
Your loaded CSS, JS, HTML bundles will be regrouped in the HWP file hence created.
The links to each loaded files will be automatically added to your HWP bundle.
Keep in mind that the HWP file's body comes virgin of any text, so, how reach HTML DOM elements in these conditions ?*
If you use Reactjs or other JavaScript library for building user interfaces, you will need to reach some DOM elements.
To include theses DOM elements in your HWP, you have just to load a template file. The content of this template will be include in your HWP bundle. So you keep an access on your DOM elements and can handle your HTML code, great.
To create a template, enter these parameters in your webpack.config.js :
plugins: [
new HtmlWebpackPlugin({
(...)
template: "path to your template.html",
(...)
})
];
Keep in mind that your path will be influenced by the context of your webpack.config.js.
It's up to you now

How do you configure Create React App to use CSS Blocks?

CSS blocks just went open source and I wanted to incorporate it into my React app while still using the boilerplate CRA webpack because I want to keep all the other functionality.
From what I understand the majority of the configuration is simply adding another babel-loader with the css-block plugin.
So instead of just:
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
You follow it with:
{
test: /\.[j|t]s(x?)$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
presets: [require.resolve("babel-preset-react-app")],
cacheDirectory: true,
compact: true,
}
},
// Run the css-blocks plugin in its own dedicated loader because the react-app preset
// steps on our transforms' feet. This way, we are guaranteed a clean pass before any
// other transforms are done.
{
loader: require.resolve('babel-loader'),
options: {
plugins: [
require("#css-blocks/jsx/dist/src/transformer/babel").makePlugin({ rewriter: CssBlockRewriter }),
],
cacheDirectory: true,
compact: true,
parserOpts: {
plugins: [
"jsx",
"doExpressions",
"objectRestSpread",
"decorators",
"classProperties",
]
}
}
},
But, I cannot for the life of me get the second bit to parse anything. It's like it doesn't even exist and my CSS modules are just being referenced inside the class. Result ends up being like:
<div class="/src/test.css">
instead of
<div class="a b cD">
If anyone has any pointers of where I should try to look I would greatly appreciate it!
P.S. For reference I'll include links to the docs below since it's very new
http://css-blocks.com/
https://github.com/linkedin/css-blocks/blob/master/packages/%40css-blocks/website/config/webpack.config.dev.js
I get the example from Linkedin example /website and works fine with react-create-app scripts.
Fallow boilerplate extracted from CSS Blocks by me ralfting/boilerplate-css-blocks... Maybe this help you.

Improve CSS debugging experience in WebPack

I have recently moved to WebPack (v3) from a Gulp based build system, and for the most part its pretty good. I am however struggling to get the CSS development experience to match what I previously had.
I write my CSS using SASS and then use the following setup in WebPack
Module.Rules:
{
test: /\.(s*)css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: { minimize: isProd }
},
{
loader: "postcss-loader"
},
{
loader: 'sass-loader'
}
],
})
},
Plugins:
new ExtractTextPlugin({
filename: 'app.bundle.css',
disable: !isProd
}),
So when I am in develpoment i.e. !isProd the ExtractTestPlugin is disabled and it uses the fallback of style-loader. This allows Hot CSS replacement. Without this the entire page would have to be refreshed to show CSS updates.
This all works great, I change CSS and a split second later its shown on screen, however, trying to debug what file or rule a CSS selector is in is proving problematic.
In this case I want to see what style is causing the font-size to be 1.5rem. I dont believe it to be in my CSS (I think its a third party library) but its nigh on impossible for me to find out the cause (I have ~50 inline styles added) and clicking the style tag link (which would previously take me to the CSS file with correct line number) now just takes me to the start of the <style> tag.
How can I improve this experience? I'd be happy with a single app.bundle.css file that is linked normally (not inline - so I get line numbers) but I really want to keep HMR for CSS.
It turns out that by adding source maps it effectively masks the delivery method (style tags) and gives the browser direct links to the source code which works correctly.
See this github post for some information.
Here is my final CSS WebPack code
{
test: /\.(s*)css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: { minimize: isProd, sourceMap: true }
},
{
loader: "postcss-loader",
options: { sourceMap: true }
},
{
loader: 'sass-loader',
options: { sourceMap: true }
}
],
})
},

How to remove unused CSS using webpack 4?

I am having problem removing unused CSS in webpack 4. It seems that most of the CSS purification plugins are dependent on extract text plugin which is not updated for version 4.
Here's my commands:
node_modules/.bin/webpack --mode=development --env.operation=separateCSS
OR
node_modules/.bin/webpack --mode=development --env.operation=bundleCSS
Here's part of my webpack.config.js:
rules: [
// Loader for SASS files
{
test: /\.s[ac]ss$/,
use: [
// Use IIFE to choose how to emit the CSS: 1. Extract as separate file 2: Bundle with the JS file
(() => {
return env.operation == "separateCSS" ? MiniCssExtractPlugin.loader : 'style-loader';
})(),
{
loader: 'css-loader',
options: {
importLoaders: 1,
url: true
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
// Write future-proof CSS and forget old preprocessor specific syntax.
// Use the latest CSS syntax today with cssnext.
// It transforms CSS specs into more compatible CSS so you don’t need to wait for browser support.
// It parses CSS and add vendor prefixes to CSS rules using values from Can I Use.
// https://github.com/MoOx/postcss-cssnext
require('postcss-cssnext')()
]
}
},
'sass-loader'
]
}
],
plugins: [
new MiniCssExtractPlugin({
filename: "../css/[name].css"
})
]
Does anybody know how can I modify my config file so webpack can remove unused CSS?
Have you considered using something called uncss. There's a webpack plugin for it. It will look through all your CSS and compare it to your HTML, and remove anything that you're not using.
Take a look: WebPack UnCSS

Resources