pseudo-selector :host not "compiled" - css

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

Related

webpack: understanding source maps when working with CSS

Introduction
I have already setup bundling for my Javascript files with webpack in my project. Now I am in the process of adding CSS files to the webpack configuration. So far, I have been including the CSS files manually in the HTML header by adding <link> elements for every CSS file I depend on (e.g. bootstrap, my own css, etc.). Obviously this is not very elegant and using webpack would be much better, so I would like to replace the link elements and bundle them via webpack.
This should be easy, everything is pretty much documented in the webpack documentation. After reading the documentation and experimenting a bit with webpack I have arrived at the configuration below which already works.
Problem
The problem with my current setup is that I would like to have proper source map support and that does not seem to work. By proper, I mean that I expect that when I run a development build with webpack and I inspect some element in Chrome DevTools, that I will see from which file and which line in the file a certain CSS class originated and that I can click on the CSS rules and the browser jumps to that file.
I do not want to have inline styles in the head element, because then the browser will show something like .foobar { <style>..</style>, rather then .foobar { app.css:154.
With my current setup I have all CSS files combined (but not minified) into one app.css file. This means that if I inspect a bootstrap class such as .btn then it appears as .btn { app.css:3003. However, what I want to achieve is that the browser shows it as .btn { bootstrap.css:3003.
So now I am trying to understand how webpack and the different plugins such as css-loader and min-css-extract-plugin apply CSS source maps, and how I can configure them to achieve a proper debugging experience.
I am not sure how relevant this is, but when I navigate in DevTools under Sources to webpack://./bootstrap/dist/css/bootstrap.css I see that it only contains a single line:
// extracted by mini-css-extract-plugin.
Webpack Setup
index.js:
window.jQuery = require('jquery/dist/jquery');
require('bootstrap/dist/css/bootstrap.css');
require('bootstrap/dist/js/bootstrap');
/* other dependencies */
webpack.config.js:
const devMode = process.env.NODE_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module: {
rules: [
{ /* Javascript rules excluded */ },
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
plugins: [
new UglifyJSPlugin (),
new HtmlWebpackPlugin({
template: 'app/index.tpl.html'
}),
new MiniCssExtractPlugin({ filename: devMode ?
'[name].css' :
'[name].[hash].css'
})
],
Conclusion
It seems I just passed the rubber duck test. While I was writing this I arrived at a solution. I will still publish the question, maybe it can help others.
The problem was that I was also using the mini-css-extract-plugin for development and not just for production. I thought that I needed to do that, because when at first I was using the style-loaded I would get styles included in the header and the browser would show me all styles as .foobar { <style>..</style>.
However, the actual problem seemed to be, that I was not using devtools. So the solution was to add devtool: devMode ? 'cheap-module-eval-source-map' : 'source-map', to the webpack configuration to conditionally use the style-loader plugin during development builds and mini-css-extract-plugin during production builds.
webpack.config.js
{
test: /\.css$/,
use: [
{
- loader: MiniCssExtractPlugin.loader,
+ loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
]
},
/* ... */
+ devtool: devMode ? 'cheap-module-eval-source-map' : 'source-map',

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

Adding less support to a production webpack configuration (from Facebook's create-react-app)

I have forked (or ejected) off Facebook's create-react-app project, with the requirement to add a few additional tools (e.g. testing, redux, less etc.), and the perhaps naive assumption that straying a bit off the path wouldn't be too much of a problem.
I think I have just about managed to add less using the following webpack.config.dev.js:
//......
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'eslint',
include: paths.appSrc,
}
],
loaders: [
// Process JS with Babel.
{
test: /\.js$/,
include: paths.appSrc,
loader: 'babel',
query: require('./babel.dev')
},
{
test: /\.css$/,
loader: 'style!css!postcss'
},
{
test: /\.less$/,
loader: 'style!css!postcss!less'
},
{
test: /\.json$/,
loader: 'json'
},
//......
}
]
},//.....
I have left the CSS loader in there (perhaps incorrectly) so that I can bring in the react/bootstrap library. Perhaps there is a better way of doing this.
Anyway, I am confused about how to add a pre-processor into webpack.config.prod.js. Here is a snippet (with Facebook's helpful comments):
loaders: [
// Process JS with Babel.
{
test: /\.js$/,
include: paths.appSrc,
loader: 'babel',
query: require('./babel.prod')
},
// The notation here is somewhat confusing.
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader normally turns CSS into JS modules injecting <style>,
// but unlike in development configuration, we do something different.
// `ExtractTextPlugin` first applies the "postcss" and "css" loaders
// (second argument), then grabs the result CSS and puts it into a
// separate file in our build process. This way we actually ship
// a single CSS file in production instead of JS code injecting <style>
// tags. If you use code splitting, however, any async bundles will still
// use the "style" loader inside the async code so CSS from them won't be
// in the main CSS file.
{
test: /\.css$/,
// "?-autoprefixer" disables autoprefixer in css-loader itself:
// https://github.com/webpack/css-loader/issues/281
// We already have it thanks to postcss. We only pass this flag in
// production because "css" loader only enables autoprefixer-powered
// removal of unnecessary prefixes when Uglify plugin is enabled.
// Webpack 1.x uses Uglify plugin as a signal to minify *all* the assets
// including CSS. This is confusing and will be removed in Webpack 2:
// https://github.com/webpack/webpack/issues/283
loader: ExtractTextPlugin.extract('style', 'css?-autoprefixer!postcss')
// Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
},
How can I add a less pre-processor step in a stable and performant way?
For context my index.js imports look as follows:
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import { CommentsSectionContainer } from './components/CommentsSection';
import './index.less';
Install less and less-loader from npm or yarn:
npm install --save-dev less less-loader
Follow this link to install extract-text-webkit-plugin:
https://github.com/webpack/extract-text-webpack-plugin
First you need to add the loader in the loaders array, after css probably makes sense for readability. It will look like this:
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
Then initialize the plugin in the plugins array:
new ExtractTextPlugin('[name].css')
Thaaaaaat should do it with another yarnpkg start

Resources