Import/apply CSS files with webpack - css

I am and have always been bad with webpack, but this time I am beaten...
Thats sounds easy : I just want to import my apply my CSS.
He is my project structure :
/src
|_assets/
| |_index.html
|_components/
| |_App.js
| |_WelcomeLogo.js
|_styles/
| |_welcomeLogo.css
|_index.js
So, index.js imports App.js, which import WelcomeLogo.js, and js is rendered properly.
WelcomeLogo.js import welcomeLogo.css : import './../styles/welcomeLogo.css';
And here is my webpackConfig :
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const path = require('path');
const autoprefixer = require('autoprefixer');
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js|jsx$/,
exclude: [
/node_modules/,
/tests/
],
use: { loader: 'babel-loader' }
},
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()]
}
}
]
}
]
},
output: {
path: path.resolve(__dirname, './dist'),
filename: process.env.production ? `index.[chunkHash].js` : `index.[hash].js`
},
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3030,
open: true
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'BananaHammock.io',
template: 'src/assets/index.html',
meta: {
'http-equiv': 'cache-control',
'content': 'no-cache'
}
}),
]
};
So the issue is, no CSS is applied to my output App...
It is the first time to not manage to do that, and feel kind of lost.
Thanks for your help.
Webpack version : 4.41.2
npm run build shows that the css is found, and parsed... But its content is not a part of the bundle :
-> % npm run build
> xxxxxx#1.0.0 build /Users/xxxx/Documents/workspace/javascript/xxxx.io
> webpack --mode production
Hash: 480520f961b41a464f93
Version: webpack 4.41.2
Time: 2137ms
Built at: 03/17/2020 9:19:56 PM
Asset Size Chunks Chunk Names
index.480520f961b41a464f93.js 134 KiB 0 [emitted] [immutable] main
index.html 822 bytes [emitted]
Entrypoint main = index.480520f961b41a464f93.js
[7] ./src/index.js 184 bytes {0} [built]
[12] (webpack)/buildin/harmony-module.js 573 bytes {0} [built]
[15] ./src/styles/welcomeLogo.css 573 bytes {0} [built]
[17] ./node_modules/css-loader/dist/cjs.js!./src/styles/welcomeLogo.css 235 bytes {0} [built]
+ 16 hidden modules
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/assets/index.html 927 bytes {0} [built]
[2] (webpack)/buildin/global.js 472 bytes {0} [built]
[3] (webpack)/buildin/module.js 497 bytes {0} [built]
+ 1 hidden module
If I use MiniCssExtractPlugin, it generates a css file... But empty.
And my welcomeLogo.css file isn't empty, and is correct according to W3C validator...

I think the css importation path is wrong. it should be '../styles/welcomeLogo.css'.

Related

Why is my webpack config not compiling my css?

i am trying to compile my css via webpack, it gives me a succes on my javascript file but doesnt say anything about my css file
this is my webpack config
`import path from 'path';
import webpack from 'webpack';
import * as MiniCssExtractPlugin from 'mini-css-extract-plugin';
import loader from 'sass-loader';
const extractSASS = new MiniCssExtractPlugin.default({filename: "app.min.css"});
const jQuery = new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
});
export default {
mode: "production",
entry: {
main: [
"./src/js/index.js"
],
},
output: {
filename: "app.min.js",
path: path.resolve("./../wwwroot/dist")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
],
test: /\.scss$/,
use: [
{
loader: "postcss-loader",
options: {
config: {
path: path.resolve(import.meta.url, "postcss.config.js")
}
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
use: "file-loader?name=images/[name].[contenthash].[ext]"
}
]
},
plugins: [
extractSASS,
jQuery
]
};`
this is the output of npm run build
npm run build
> cms3#1.0.0 build
> webpack --mode=production
asset app.min.js 169 KiB [compared for emit] [minimized] (name: main) 1 related asset
runtime modules 500 bytes 2 modules
cacheable modules 504 KiB
./src/js/index.js 88 bytes [built] [code generated]
./node_modules/bootstrap/dist/js/bootstrap.js 134 KiB [built] [code generated]
./node_modules/jquery/dist/jquery.js 283 KiB [built] [code generated]
./node_modules/popper.js/dist/esm/popper.js 86.4 KiB [built] [code generated]
webpack 5.75.0 compiled successfully in 3469 ms
Most likely webpack thinks that no CSS files are needed in your build.
You need to tell webpack by adding an import line in your index.js file:
import "./path/to/my.scss";

Webpack + postcss not purging Tailwind

I'm trying to use webpack 5 and tailwind 2. The logs suggest that most things are set up correctly, but no purging is taking place.
I run NODE_ENV=production webpack --config webpack.prod.js
I have the following webpack configuration
mode: 'production',
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/i,
use: ['style-loader', 'css-loader', {
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
require("tailwindcss")("./tailwind.config.js"),
require("autoprefixer"),
],
},
}
}, "sass-loader"],
}
tailwind.config.js
module.exports = {
purge: {
mode: 'layers',
layers: [],
content: ['./src/*.elm', './src/**/*.elm'],
},
theme: {
extend: {}
},
variants: {},
plugins: []
};
My production builds are still yielding 4mb bundles which tells me that no purging has taken place. I think I struggled before and switched to putting the options in a separate postcss.config.js but that shouldn't always be necessary?
In the command line logging I see
cacheable modules 4.14 MiB (javascript) 7.64 KiB (asset)
modules by path ./src/ 4.13 MiB (javascript) 7.64 KiB (asset)
modules by path ./src/*.scss 1.34 KiB
./src/styles.scss 439 bytes [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[0].use[2]!./node_modules/sass-loader/dist/cjs.js!./src/styles.scss 930 bytes [built] [code generated]
./src/index.js + 1 modules 754 bytes [built] [code generated]
./src/Main.elm 159 KiB [built] [code generated]
./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[0].use[2]!./node_modules/sass-loader/dist/cjs.js!./src/tailwind.css 3.98 MiB [built] [code generated]
Try this:
module.exports = {
purge: {
mode: 'layers',
enabled: true, // This fixed it for me
layers: [],
content: ['./src/*.elm', './src/**/*.elm'],
},
theme: {
extend: {}
},
variants: {},
plugins: []
};

MiniCssExtractPlugin doesn't link with my html file

When i Webpack my project using MiniCssExtractPlugin to separate css into files, it creates the main.css file but never write the link into my html file.
Here is my webpack.config.js :
const webpack = require("webpack");
const path = require("path");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const dev = process.env.NODE_ENV ==="dev"
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
let cssloaders = [MiniCssExtractPlugin.loader, {loader: 'css-loader', options:{importLoaders: 2, modules: true } } ]
if(!dev) {
cssloaders.push( {
loader: 'postcss-loader',
options : {
plugins: (loader) => [
require('autoprefixer')( { browsers : ['last 2 versions', 'ie > 8']
}),
]
},
})
}
let config = {
mode : 'none',
entry: "./assets/js/app.js" ,
output: {
path: path.resolve(__dirname, "./dist"),
filename: "bundle.js",
publicPath: "/wp/dist/"
},
devtool : dev ? "cheap-module-eval-source-map" : "source-map",
watch : dev,
module : {
rules : [
{
test : /\.js$/,
exclude: /(node_modules|bower_components)/,
use : [
'babel-loader'
]
},
{
test : /\.css$/,
use: cssloaders
},
{
test : /\.scss$/,
use:
[
...cssloaders,
'sass-loader'
]
,
},
]
},
plugins : [
new MiniCssExtractPlugin({
filename : '[name].css',
chunkFilename: "[id].css"
})
],
optimization : {
minimize : !dev
}
}
if(!dev){
config.plugins.push(new UglifyJsPlugin({
sourceMap : true
}))
}
module.exports = config;
So the loaders are in correct order : postcss-loader (if not in dev), sass-loader (for scss test), css-loader and MiniCssExtractPlugin.
When I webpack, the main.css fil is well emitted, but the html file doesn't have the link href in the head written...so there is no css :-)
bundle.js 4.85 KiB 0 [emitted] main
main.css 67 bytes 0 [emitted] main
I think i miss something ?
Thank you in advance !
It's normal behavior because mini-css-extract-plugin only help you to extract css into seperate css file instead of include css in js file.
You need to use html-webpack-plugin to include your css into html otherwise you have to add css in your html manually
I just add the main.css file to my HTML manually, without needing to install any extra plugins. I'm ok with this because the file never changes its name.
<link rel="stylesheet" href="/public/css/main.css">

webpack 4, bundle glyphicons

I have issues understanding how to bundle glyphicons using webpack.
Here is my webpack file
module.exports = {
context: path.join(__dirname, "app"),
devtool: 'source-map',
entry: {
main: ["./main.coffee"],
vendor: ["./vendor.coffee"]
},
resolve: {
extensions: [".coffee", ".js", ".json", ".css", ".less", ".html"]
},
output: {
path: path.join(__dirname, 'wwwroot'),
filename: '[name].js',
chunkFilename: '[id].chunk.js',
},
module: {
rules: [
{
test: /\.coffee$/,
use: ['coffee-loader'],
exclude: /node_modules/
},
{
test: /\.less$/i,
use: css.extract({
fallback: "style-loader",
use: ['css-loader', 'less-loader']
}),
exclude: /node_modules/
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
]
},
plugins: [
css,
new cleanWebpackPlugin(["./wwwroot"])
],
optimization: {
splitChunks: {
minSize: 2,
name: true
}
}
}
here is the output I get from webpack
Child extract-text-webpack-plugin ../node_modules/extract-text-webpack-plugin/dist ../node_modules/css-loader/index.js!../node_modules/less-loader/dist/cjs.js!app.less:
[0] ../Content/fonts/glyphicons-halflings-regular.eot 26.5 KiB {0} [built]
[1] ../Content/images/nice_snow.png 23.9 KiB {0} [built]
[2] ../Content/fonts/glyphicons-halflings-regular.svg 82.2 KiB {0} [built]
[3] ../Content/fonts/glyphicons-halflings-regular.ttf 53.7 KiB {0} [built]
[4] ../Content/fonts/glyphicons-halflings-regular.woff 30.4 KiB {0} [built]
[7] ../node_modules/css-loader!../node_modules/less-loader/dist/cjs.js!./app.less 139 KiB {0} [built]
+ 2 hidden modules
here is how i import glyphicons (it resolves path fine, you can tell by webpack output message)
#font-face {
font-family: 'Glyphicons Halflings';
src: url('../#{icon-font-path}#{icon-font-name}.eot');
src: url('../#{icon-font-path}#{icon-font-name}.eot?#iefix') format('embedded-opentype'),
url('../#{icon-font-path}#{icon-font-name}.woff') format('woff'),
url('../#{icon-font-path}#{icon-font-name}.ttf') format('truetype'),
url('../#{icon-font-path}#{icon-font-name}.svg#glyphicons-halflingsregular') format('svg');
}
Finally here is a folder structure i get for the output
- wwwroot
1. app.css
2. app.css.map
3. main.js
4. main.js.map
5. vendor.js
6. vendor.js.map
Now, everything working as expected. all java script is bundled and css as well. only glyphicons are not showing up.

Webpack not compiling sass files

I'm trying to compile all my .scss files but webpack doesn't seem to be doing it, even though I've declared style-loader & sass-loader in my webpack config file.
I don't see why the .scss files wouldn't compile? I've followed a guide from the following blog: http://www.jonathan-petitcolas.com/2015/05/15/howto-setup-webpack-on-es6-react-application-with-sass.html
Loaders:
loaders: [
// Working loaders...
{test: /\.json$/, loaders: ["json"]},
{test: /\.(ico|gif|png|jpg|jpeg|svg|webp)$/, loaders: ["file?context=static&name=/[path][name].[ext]"], exclude: /node_modules/},
{test: /\.js$/, loaders: ["babel?presets[]=es2015&presets[]=stage-0&presets[]=react"], exclude: /node_modules/},
// Non working loaders...
// ALSO TRIED THIS -> { test: /\.scss$/,loader: ExtractTextPlugin.extract( "style", 'css!sass')}
{ test: /\.css$/, loader: ExtractTextPlugin.extract(
"style-loader",
"sass-loader?sourceMap",
{
publicPath: "../dist"
}
)},
],
style.css is never generated anywhere.
Plugins:
plugins: [
new ExtractTextPlugin("style.css", {
disable: false,
allChunks: true
}),
]
Also tried:
The following was copied from the blog I linked above.
Loaders:
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass')
}
Plugins:
new ExtractTextPlugin('public/style.css', {
allChunks: true
})
Other webpack configs:
Here are my other configurations. Pretty standard and do the job for everything except the .scss!
target: "node",
cache: false,
context: __dirname,
debug: false,
devtool: "source-map",
entry: ["../src/server"],
output: {
path: path.join(__dirname, "../dist"),
filename: "server.js"
},
externals: [nodeExternals({
whitelist: ["webpack/hot/poll?1000"]
})],
resolve: {
modulesDirectories: [
"src",
"src/components",
"src/containers",
"node_modules",
"static"
],
extensions: ["", ".json", ".js"]
},
node: {
__dirname: true,
fs: "empty"
}
Here is what my webpack terminal is printing out after I run it:
Waiting for dist/*.js (max 30 seconds)
[2] http://localhost:8080/webpack-dev-server/
[2] webpack result is served from http://localhost:8080/dist
[2] content is served from /Users/james/apps/react-server-side/server
[0] Ready. dist/*.js changed
[1] Hash: 12a5c90bd2564cd8880d
[1] Version: webpack 1.12.14
[1] Time: 15448ms
[1] Asset Size Chunks Chunk Names
[1] server.js 1.37 MB 0 [emitted] main
[1] server.js.map 1.23 MB 0 [emitted] main
[1] [0] multi main 40 bytes {0} [built]
[1] + 659 hidden modules
Does anyone have any ideas to what is going on?!
Edit
Forgot to add that I'm doing this server side!
Are you requiring the scss files in your js files? You have to do that.
Also, you don't need the ExtractTextPlugin, a config as the following should work:
loaders: [
// ...
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass']
}
]

Resources