Webpack 5 Split chunks not working with scss imports - css

I have a very basic webpack(v5.75.0) file setup:
webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
home: './src/home.js',
about: './src/about.js'
},
mode: "development",
resolve: {
extensions: ['.js', '.jsx', '.scss']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].js',
clean: true
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
MiniCssExtractPlugin.loader, "css-loader", "sass-loader",
],
},
],
},
plugins: [new MiniCssExtractPlugin({ filename: "css/[name].css"})],
optimization: {
splitChunks: {
chunks: 'all',
minSize: 0,
},
},
};
Home.js:
import "./home.scss";
About.js:
#import "./about.scss";
home.scss:
#import "./card.scss";
about.scss
#import "./card.scss";
My understanding is that with my splitChunk settings, this should create a seperated stylesheet, with the card css, so I can share it around the project.
However, all I get is an output of about.css and a home.scss, both containing the same card css, and no shared file is created.
interestingly, if I change both the imports in home/about.js to css instead:
#import "./card.css";
Then a separate chunk file is created, and the css is split perfectly.
Could anyone tell me what I have done wrong, please?

Answering my own question.
Turns out it was a very simple fix.
I had to import all my page specific .scss into my home/about.js file, rather than trying to make a single entry scss file (that imports all the page specific scss).
I assume #import in scss is copying the css into the file(as it should), and doesn't care about chunking, like the js does.

Related

TailwindCSS 3.0 Upgrade overriding button styles

Problem:
Button class being overridden by default tailwind base classes. Not sure why my classes on the element aren't being applied.
Question:
How can I get my styles to apply properly?
Screenshot:
As you can see background color on .documentCategory__row is being overridden by button, [type=button] on index.scss which is being defined within #tailwind/base.
/* index.scss */
:root {
--color-primary: #00a3e0;
--color-secondary: #470a68;
--color-success: #87d500;
--color-accent: #e87722;
/* Dark themes below */
--color-dark-primary: rgba(31, 41, 55, 1);
--dark-text: rgba(187, 193, 198, 1);
}
#import "tailwindcss/base";
#import "tailwindcss/components";
#import "tailwindcss/utilities";
I'm not sure if this has to do with me switching to dart-scss so here is my webpack configuration in case I am missing something
import path from 'path'
import { Configuration as WebpackConfiguration, HotModuleReplacementPlugin } from 'webpack'
import { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';
import HtmlWebpackPlugin from 'html-webpack-plugin'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import ESLintPlugin from 'eslint-webpack-plugin'
import tailwindcss from 'tailwindcss'
import autoprefixer from 'autoprefixer'
const CopyPlugin = require('copy-webpack-plugin');
interface Configuration extends WebpackConfiguration {
devServer?: WebpackDevServerConfiguration;
}
const config: Configuration = {
mode: 'development',
devServer: {
static: path.join(__dirname, 'build'),
historyApiFallback: true,
port: 4000,
open: true,
hot: true,
},
output: {
publicPath: '/',
},
entry: './src/index.tsx',
module: {
rules: [
{
test: /\.(ts|js)x?$/i,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
},
},
},
{
test: /\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
{
loader: 'postcss-loader', // postcss loader needed for tailwindcss
options: {
postcssOptions: {
ident: 'postcss',
plugins: [tailwindcss, autoprefixer],
},
},
},
],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: 'file-loader',
options: {
outputPath: '../fonts',
},
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
}),
new HotModuleReplacementPlugin(),
new CopyPlugin({
patterns: [
// relative path is from src
{ from: 'public/images', to: 'images' },
],
}),
// Add type checking on dev run
new ForkTsCheckerWebpackPlugin({
async: false,
}),
// Add lint checking on dev run
new ESLintPlugin({
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
devtool: 'inline-source-map',
};
export default config
If there are other files I am missing that are needed let me know!
without seeing what your index.tsx looks like I can only make a guess, but here's what caused this issue in our app:
in our index.tsx we were importing index.css after importing our component tree with import App from 'src/App. thus the css was loaded into the site in the wrong order. imports from components first (css modules, normal css imports), tailwind last.
go to your entry file (probably index.tsx) and try moving your import 'index.scss' line above importing the root component.
like this for example
/* index.tsx */
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'; // this file holds all tailwind styles
import { App } from 'src/App';
// ...
read more here:
https://github.com/tailwindlabs/tailwindcss/discussions/7304#discussioncomment-2256226
Even i faced the same issue but I am using Vue3 + element-ui-plus, after spending more than 6 hours my solution is to set :native-type='null':
<el-button type='primary' round #click='handleClick' :native-type='null'>Click Me</el-button>
but this is kinda "hack", this either need to be fixed by Tailwind or by element-ui team. Anyhow, for now enjoy ;)
And the discussion is on here
I got the same issue using tailwindcss v3 and NextUI, and button's background were "transparent". By adding type = {null}, to button's I solve the issue

Minimize SCSS to CSS with webpack keeping file/folder structure

I am having trouble understanding how to compile and minify my scss files to css, while keeping the same folder and file structure. I am using MiniCssExtractPlugin to extract everything, as well as style-loader, css-loader, postcss-loader, and sass-loader
Here is the file structure in my src folder
app.scss contains all the imports. importing from folders 1-7. I am first having trouble with the imports, and then have trouble compiling and minimizing the remaining scss files.
The end goal is to have an compiled folder look like this with each file being minimized and app.scss bundle all the imports
Here is a run down of the code I have so far for webpack.config.js
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css',
chunkFilename: '[id].css'
})
],
module: {
rules: [
{
test: /\.(scss|css)$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: 'sass-loader', options: { sourceMap: true } },
]
}
]
},
optimization: {
minimizer: [new TerserJSPlugin({extractComments: false}), ],
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](lodash)[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
When running this code, I just get an app.css file under a css folder that does not have imports included, and no other files are included as well. Can someone help my understand the process I need to take? I've been all over docs for each loader and not really understanding what I am looking for.
Thanks!

Webpack build successfull but styles.css file style is not reflecting

I am developing a web application in angular 5.Now I have included webpack 4 in my application.But There is a problem all styles written in styles.css file are not reflecting in the build created from webpack.
Need solution for this problem.
Below is my webpack.common.js file which is used for loading diffrent types of files present in my application build always succeed but the styles.css code is not reflection on my site when it gets loaded in browser.But code written in components .scss file reflects properly i have searched a lot but did not find any solution for this issue why is is happening.
import styles from './styles.css';
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfill': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loader: ['awesome-typescript-loader','angular2-template-loader','angular-router-loader'
],
exclude:[/node_modules/]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/images/[name].[hash].[ext]'
},
{
test: /\.(css|scss)$/,
include: helpers.root('src', 'app'),
loaders: ['css-loader']
},
{
test: /\.js$/,
include: helpers.root('src', 'app'),
loader: 'babel-loader',
exclude:[/node_modules/],
query:{
presets:['es2015']
}
}
]
},
plugins: [
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)#angular/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new ExtractTextPlugin("src/styles.css"),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
You should import your css stylesheet using #import from your main css/scss stylesheet.
Do NOT import a css file as a javascript module from the webpack config file. This has no sense.

Webpack throwing error on SCSS #import SCSS

I'm trying to process multiple SCSS files into a single external CSS file in Webpack (3.6.0) except I'm encountering issues around the parsing of the #import statements.
Entry index.js contains:
import './styles/main.scss';
Entry SCSS:
#import 'reset.scss';
#import 'global.scss';
#import 'fonts.scss';
#import 'system.scss';
Current webpack:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js'
},
context: path.resolve(__dirname),
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
},
plugins: [
new CleanWebpackPlugin(['app']),
new HtmlWebpackPlugin({
title: 'Minimum-Viable',
filename: 'index.html',
template: './public/index.html',
}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'es2015',
'react',
],
plugins: ['transform-class-properties'],
},
},
},
{
test: /\.scss$/,
include: [
path.resolve(__dirname, 'styles')
],
use: [
{loader:'style-loader'},
{loader:'css-loader'},
{loader:'sass-loader'}
]
},
],
},
resolve: {
extensions: ['.js','.scss']
}
};
The Error being thrown is:
ERROR in ./src/styles/main.scss Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type. | #import 'reset.scss';
Any pointers gratefully received.
I managed to reproduce the error and it seems to come from:
include: [
path.resolve(__dirname, 'styles')
],
The path is the issue cause the loader searches for /styles in ./styles but looking at your entry point:
entry: {
app: './src/index.js'
},
It should actually be ./src/styles so:
include: [
path.resolve(__dirname, 'src', 'styles')
],
with:
include: [
path.resolve(__dirname, 'styles')
],
you are instructing webpack to use your loader chain only on files residing in your styles folder.
reset.scss looks like a node dependency usually stored in your node_module, which is excluded from SASS processing by the include option.
Try to remove your SASS include option or to extend it in order to include node_folder or the specific module imported by your styles.
I basically have the same config as you, except for two things:
{
test: /\.scss$/,
exclude: /node_modules/,
use: ["style-loader", "css-loader", "sass-loader"]
}
If your webpack is in a different folder compared to your project root, __dirname may not work out for you. You might need to remove that statement all together or change it to process.cwd(). I can give you another hint and that may be that you are missing the node-sass package. Secondly, you are probably not using the right syntax for webpack version 2 or 3 as shown in the use key.
Have you tried Extract text webpack plugin
https://github.com/webpack-contrib/extract-text-webpack-plugin
Basically it will collect all of your styles files(imported in your code) and pack it to bundled css which you can then just link to your html.
Did you try this way?
index.js:
import './styles/main.scss';
import './styles/reset.scss';
import './styles/global.scss';
import './styles/fonts.scss';
import './styles/system.scss';

Compiling a .less file to a specific .css file using webpack

I want to use webpack, to compile a style.less file to a module.css file.
I have found https://github.com/webpack-contrib/less-loader as a very popular package, which however does not seem to work for me, since I really need to create that module.css file.
So how can I do that with webpack?
Found the solution myself. The following webpack.config.js snippet works for me:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = function(env) {
return {
...
module: {
loaders: [
{
test: /.*\.less$/,
loader: ExtractTextPlugin.extract({
loader:[ 'css-loader', 'less-loader' ],
fallbackLoader: 'style-loader'
})
}
]
},
plugins: [
new ExtractTextPlugin({ filename: 'module.css', disable: false, allChunks: true })
]
};
};
Where ... is a placeholder for other parts of the config, which are not relevant here.

Resources