Webpack's config rules may seem complicated, but it really isn't! This is a simple "cheatsheet" that you can use for webpack's config.
Here is where you place the rules:
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/bundle.js",
},
mode: "development",
module: {
+ rules: [],
},
};
Your config does not have to look like the one above, I was just showing you where the rules go (in the module.rules array) and how it looks
JavaScript and JSON #
Nothing is really needed for these two languages as webpack natively supports them
CSS/SCSS #
You do need a few packages to import CSS and/or SCSS into webpack, but it works like a charm.
Install the packages needed with this command:
npm install postcss-loader style-loader sass-loader css-loader --save
Then, insert the following rule in webpack.config.js
under module -> rules:
{
test: /\.(scss|css)$/,
use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
Images #
Yes, you can use images in webpack. You will need to use the Assets modules rule functions.
Insert the following rule in webpack.config.js
under module -> rules:
{
test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
type: 'asset/resource'
},
Fonts and SVG files #
For this one, you need to use something inline assets
Insert the following rule in webpack.config.js
under module -> rules:
{
test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
type: 'asset/inline',
},
Babel #
Babel is a compiler for the next generation JavaScript, today. You can basically use newer JavaScript in older browsers like Internet Explorer.
Install the packages needed with this command:
npm i @babel/core @babel/preset-env babel-loader @babel/plugin-proposal-class-properties --save
Then, insert the following rule in webpack.config.js
under module -> rules:
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
I actually made this cheat sheet for myself, but I decided to share it with everyone! Enjoy!
Top comments (0)