webpack css loader exclude css files - reactjs

Currently, I have multiple css files under some react components. Those css files are required conditionally. However, css loader and extract text plugin include all the css files which is not required in a js file. Is there any way to exclude files by regex using test config or other way?
test: /\.css$/,
lets say I have css files
bear.css
cat.css
styles.css
colors.css
... multiptle different css files
I edit the regex correctly but still it include all css no matter what which i tested by leaving one comment on css file which should not be included on bundle.css
This is how I require css file
const css = require(`./styles/${config}`)
I will answer myself. Webpack's include exclude used to determine the file need to be transpile or not, which is nothing to do with excluding files from your bundle. For example, you add regex to exclude, it will still be in your bundle. However, it will not be processed or transpiled(depends on your loader you use).
Therefore, you should use something likeignore loader to remove from your bundle.

According to webpack documentation you can include style-loader and css-loader in your webpack.config.js file:
config = {
entry: "./app/Main.js",
output: {
publicPath: "/",
path: path.resolve(__dirname, "app"),
filename: "bundled.js"
},
mode: "development",
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-react", ["#babel/preset-env", { targets: { node: "12" } }]]
}
}
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
]
}
}
After that you could add css directly in your Main.js file
import Example from 'Example';
import './css/bear.css';
import './css/cat.css';
...

Related

How to load single css file in webpack instead of multiple files from node_modules

This is working code but it's loaded all .css file from node_modules
module: {
rules: [
{
test: /\.css$/i,
use: ["css-loader"]
}
]
}
I want load only one css file form node modules that is require in one of .js file?
i.e. file path : node_modules\package_name\dist\style\123.css.
Add in an exclude statement to your rule for the node_modules folder
module: {
rules: [
{
test: /\.css$/,
use: ["css-loader"],
exclude: /node_modules/,
}
]
}

Import Library Stylesheets With Babel-Plugin-React-Css-Modules

I am trying to include another library's css for their component in my own application. For reference, I am trying to use this data table library: https://github.com/filipdanic/spicy-datatable.
In the docs, it states Out of the box, spicy-datatable is bare-bones. Include this CSS starter file in your project to get the look from the demo. Edit it to suit your needs.
I tried to import the style sheet at the top of the component that I am building like this: import * as spicy from 'spicy-datatable/src/sample-styles.css'; in my own component file. It was not styled. I tried putting the raw code into my index.scss file in my assets/styles folder - did not work. I tried putting it in my own styles file ./component.scss - did not work.
I have them currently set up like:
import * as styles from './component.scss';
import * as spicy from 'spicy-datatable/src/sample-styles.css';
and am getting an error:
Module parse failed: Unexpected token (4:0)
You may need an appropriate loader to handle this file type.
webpack.config.js
const dirNode = 'node_modules';
const dirApp = path.join(__dirname, 'client');
const dirAssets = path.join(__dirname, 'assets');
/**
* Webpack Configuration
*/
module.exports = {
entry: {
vendor: ['lodash'],
bundle: path.join(dirApp, 'index')
},
resolve: {
modules: [dirNode, dirApp, dirAssets]
},
plugins: [],
module: {
rules: [
// BABEL
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules)/,
options: {
compact: true
}
},
// CSS / SASS
{
test: /\.(scss)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
},
'sass-loader'
]
},
// IMAGES
{
test: /\.(jpe?g|png|gif)$/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
}
};
.babelrc
"plugins": [
[
"react-css-modules",
{
"filetypes": {
".scss": {
"syntax": "postcss-scss"
}
},
"webpackHotModuleReloading": true
}
]
I'm not sure if I need to add something to specifically handle .css files, this is my first time working with CSS Modules. I thought react-css-modules did that so I'm not quite sure why the CSS file isn't loading correctly.
Edit:
Edited my webpack around to include CSS:
{
test: /\.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}
}
]
},
Error is gone, but styles still do not appear.
Could you try changing below:
import * as spicy from 'spicy-datatable/src/sample-styles.css';
to
import from 'spicy-datatable/src/sample-styles.css';
If you are using CSS-Modules, try below:
import spicy from 'spicy-datatable/src/sample-styles.css';
and then use the style on JSX element like below:
<h1 className={classes.<className in CSS here>}>
I setup a codesandbox with the spicy-datatable library and imported the styles and looks like it applied. The styles are in "Hello.css" file and it is imported in "index.js".
https://codesandbox.io/s/4j31xj3689
If library doesn't use css-modules (uses className attribute instead of styleName) we need to disable modules for imported css, so the class names will remain unchanged. This can be done in 2 ways:
Modify your Webpack config
module: {
rules: [
{
test: /\.(css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: false
}
}
]
},
...
]
}
Import library css directly into your scss stylesheet (thanks to this answer pointing out how to perform proper .css import). Make sure to exclude .css file extension from import line. :global directive will prevent css-modules to modify class names for all styles within this directive.
:global {
#import "~library-module-name/.../CssFileWithoutExtension";
}

react-toolbox css config in webpack 2 not working

I am working with webpack and I have been trying to config react-toolbox library.
I managed to make it work but the css is not loading.
webpack.config.js
You haven't configured your style loader to emit CSS modules
Add this to your style loader
loader: 'style!css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'
This will turn on CSS modules, and also set it up for allowing postCSS to hook up to it
Remember that this will now treat any .scss or .css file as a locally scoped module, so if you have any separate normal SCSS or CSS that you want to remain global, you will need to add another rule for them
// EDIT
It may be confused using the loader string if your other loader configs are still in that array (as the above string is shorthand to combine them all), try instead separately using config objects...
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
localIdentName: '[name]__[local]___[hash:base64:5]',
modules: true
}
},
{
loader: 'postcss-loader',
options: {
plugins: [
postcssNext
]
}
}
]
}
React Toolbox no longer uses SCSS having migrated to PostCSS so I've left that out - if you use it then add that in the same manner

How to implement scss in react

I am trying to implement SCSS in my project. I have ran the npm command to install the loader "npm install sass-loader node-sass --save-dev". I have created a scss file. but the problem is it is not working. i tried multiple configurations to make it runable but no luck. below are my webpack configuration. please advice,
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}]
Did you configure your loaders correctly? Cant at least see any css/scss loaders in your provided code? https://github.com/webpack-contrib/sass-loader
UPDATE::
Add ExtractTextPlugin into your config. What this does is, it moves all the require("style.css")s in entry chunks into a separate single CSS file. So your styles are no longer inlined into the JS bundle, but separate in a CSS bundle file (styles.css) https://github.com/webpack-contrib/extract-text-webpack-plugin
Include the following into your webpack.config file.
// webpack.config.js
import ExtractTextPlugin from 'extract-text-webpack-plugin'
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
loader: [
'css',
'postcss',
{
loader: 'sass',
query: {
sourceMap: false,
}
}
],
})
}
and import your .scss files ::
import 'scss/myfile.scss'

Configuring CSS modules in development/production with webpack and React

How can use CSS modules in production and load standard css file in production?
I am configuring an new application with React using webpack
In development I use CSS modules using webpack loaders :
into my .jsx file I import the style file:
import style from './stile.scss';
export class App extends React.Component {
render() {
return (
<div>
<div>
<span className={style.title}>Ciao</span>
</div>
</div>
)
}
}
then I use the following webpack configuration for loaders for my stylesheets:
loaders: [
{
test: /\.(scss|css)$/,
loader: 'style-loader!css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap'
}
]
this way everything works (the style is included in the .js file and classes properly hased)
but in production? I should leave the browser render all the classes included in the webpack bundle.js output file?
I would rather create a css file with webpack (and ExtracttextPlugin) with all my style:
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('css-loader' )
}
and link the .css produced in my index.html
Problem is that now all my classes definitions into the React components are no longer rendered in the browser.
How should I solve this?
You can't just switch from using CSS modules to not using them, that doesn't work out as your code depends on it. Also there is no reason not to use CSS modules in production as well. What you want to change is not the CSS modules, but the way you include the CSS. Instead of having it in your JavaScript bundle you can extract them with extract-text-webpack-plugin into a separate .css file, but you still need to use the same configuration for the loaders.
webpack 1
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap&modules&importLoaders=1&localIdentName=[name]-[local]___[hash:base64:5]!sass-loader?sourceMap')
}
The first argument style-loader is only used as a fallback if the CSS can't be extracted.
webpack 2
The arguments to ExtractTextPlugin.extract changed and for readability using options instead of an inline query in the string.
{
test: /\.(css|scss)$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
importLoaders: 1,
localIdentName: '[name]-[local]___[hash:base64:5]'
}
},
{ loader: 'sass-loader', options: { sourceMap: true } }
]
})
}

Resources