Saturday, March 11, 2023
HomeReactThe right way to CSS with Webpack 5

The right way to CSS with Webpack 5


This tutorial is an element 2 of 4 in ‘Webpack with Model’-series.

This tutorial is an element 2 of three in ‘Webpack with Font’-series.

In case you occur to have a customized Webpack setup, chances are you’ll be questioning how you can arrange CSS with Webpack. This brief tutorial walks you thru the method. To start with, it is advisable to set up a CSS loader and a method loader to your dev dependencies:

npm set up --save-dev css-loader type-loader

And second, you need to use each loaders for all CSS information in your Webpack configuration:

...

module.exports = {

...

module: {

guidelines: [

...

{

test: /.(css)$/,

use: ['style-loader', 'css-loader'],

},

],

},

...

};

Then in a brand new src/type.css file, add some CSS to it:

h1 {

colour: purple;

}

And in your src/index.js file, or another JS file, import this new CSS file:

import './type.css';

That is it. From right here you need to use CSS in your JavaScript challenge which is powered by Webpack.

CSS with Webpack in Manufacturing

In case you occur to have a , you will want a distinct configuration for manufacturing when utilizing CSS.

First, set up the MiniCssExtractPlugin for Webpack to your dev dependencies:

npm set up --save-dev mini-css-extract-plugin

And second, use it in your Webpack’s manufacturing configuration as a substitute of favor loader and moreover as a plugin:

...

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {

mode: 'manufacturing',

module: {

guidelines: [

{

test: /.(css)$/,

use: [

MiniCssExtractPlugin.loader,

'css-loader',

],

},

],

},

plugins: [

new MiniCssExtractPlugin(),

...

],

...

};

That is it. When you construct your challenge with Webpack, you will notice the type information exhibiting up in your dist/ folder.

This tutorial is an element 2 of 4 in ‘Webpack with Model’-series.

This tutorial is an element 2 of three in ‘Webpack with Font’-series.

RELATED ARTICLES

Most Popular

Recent Comments