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.
Related
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
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',
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
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 }
}
],
})
},
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