Creating modules in JavaScript using Webpack and Babel — Part 2

In the first part of this tutorial, we discussed the prerequisites and some new concepts. In this part, we’re gonna learn how to let webpack compile our ES6+ code into an old version of JavaScript, how to import our stylesheets into our JS file and how to use images also.

If you haven’t read Creating modules in JavaScript using Webpack and Babel — Part 1, please do so in order to be able to follow along with us in this tutorial.

Installing babel:

module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
],
},

Now run again npm start and everything should work perfectly.

Installing css-loader and style-loader:

{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},

Now let’s import our stylesheet into our index.js file. Type at the very top of index.js import ‘./styles.css’;. Inside styles.css change the background of the page:

body {
background-color: aqua;
}

Now run in the terminal npm start and refresh the page, You should see a new background colour instead of the default white one.

Let’s celebrate 🥳. Styling our code without linking any stylesheet in our HTML file is an accomplishment, isn’t it??

Using Asset Modules to load our images:

body {
background: url('./images/<your image name.its extension>');
background-size: cover;
}

Don’t forget to change <your image name.its extension> to the actual name of your image, background: url('./images/bg.jpg'); in my case.

If you’ve killed the terminal, run npm start again. You notice an error right??

Webpack Error Screenshot

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. From this line, you can understand that webpack needs a new loader to process the images. However, as of webpack 5, using the built-in Asset Modules we can easily incorporate those in our system as well. Add these lines of code to the rules array in the webpack.config.js file:

{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},

Now simply import the image into your index.js file import './images/<your image name.its extension>';. Kill the terminal and run it again. Refresh the browser and BOOM. There it is. Your project background is now changed.

With this boilerplate, you’re able to create different JS files and import them via this command import nameOfTheModule from 'pathOfTheModule'; into the index.js, and the whole code will be bundled into one single JS file 😉

It was quite a long journey, but you did it. Congrats.

celebration gif

If you want to use it, here’s the source code for this tutorial.

I hope that you got benefited from this tutorial. Thanks for your time and see you in the next articles 😊

My: Portfolio, GitHub, LinkedIn

Full Stack Developer