DEV Community

Cover image for Mastering Webpack
Kinanee Samson
Kinanee Samson

Posted on

Mastering Webpack

Webpack for Beginners Series

Familiarize yourself with webpack, learn how to use webpack to transpile your ES6 and Typescript using webpack

In this article we will see how we can use webpack to convert JavaScript that is written with ES6 syntax into an older version of JavaScript that older browsers can understand, we will also see how to use webpack to convert TypeScript into JavaScript. We will also see how to use the json-loader to load json files into our modules.

In our previous article we saw how to use webpack to import our css files into our modules and style our web page in a clean and smart format, we also saw how to use webpack to compile our sass files into normal css. We then looked att using typescript to handle assets like images, if you missed it, you can check it here

Normally you'd write your JavaScript using the latest syntax i.e ES6 because it's cool and you should be, however there are browsers that were built before the introduction of the ES6 syntax and they can't understand it, few people still use this old browsers for some obvious reason best known to them, however we want to ensure that people with old technology can still view our website, there is a need to make our code backwards compatible and thankfully we have webpack and babel-loader for that, we need to install the dependencies we need to do this heavy lifting, so open up your terminal in the bundle-app directory and type npm i babel-loader @babel/core @babel/preset-env --save-d and press enter, grab a cup of coffee and wait for it to finish installing and then we have the required modules to do the work we need. Open up your webpack.config.js file and make the following changes to it;

You can find the code to this lesson on this repository


//webpack.config.js
const path = require('path') 


module.exports = {

    entry: './src/index.js',

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    }, 
    module: {
        rules: [
            {
                test: /\.scss$/i, 
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader' 
                ]
            },
            {
                test: /\.(png|jpg|jpeg|svg|gif)$/i,
                type: 'asset/resource'
            },
            //new addition
            {
                test: /\.js$/i,
                exclude : /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    }
}

Enter fullscreen mode Exit fullscreen mode

We have our webpack.config.js file setup to handle ES6 transpilation for us, note please depending on the version of JavaScript you are writing, you will need to install the preset for that, there are different presets for different things, like JSX e.t.c, we will look at JSX later, however you can visit the babel website to learn more about babel and it's preset. So now we can edit up our index.js file and write some ES6 syntax and we would see it converted to something the browser will understand, if you are observant, you would see an exclude property inside of the rules for the babe-loader, what this does, is to tell webpack to exclude the node_modules folder and all of it's content, when testing for files that have the .js extension, remember how we exclude a folder from being tracked by git first of all let's create a new file to use some ES6 export style and you can call it what you want but i'm gonna call mine babel.js;


const app = {name: 'my app', version: 1}
const tool = {language: 'python', framework: 'django'}

console.log({app, tool})

export default {app, tool}

Enter fullscreen mode Exit fullscreen mode

Import this file to our index.js file should not change much except for an import statement where we import from babel.js and then we run npx webpack in the command line to compile our code, when that's done we should still see the same thing in our browser, however if we inspect our bundle.js file we should see all our const and let replaced with var and other transformations. Now this is particularly helpful when we want to ensure our code is backward compatible and can run on old browsers. That is for ES6 JavaScript, you could also use different presets than we used in this example and i would advice you to visit the babel website to learn more about them.

TypeScript And Webpack

Next we move up to how we can use webpack to parse our TypeScript files into JavaScript, first of all it is important you know about Typescript and you do know how to write TypeScript code, TypeScript is a super set of JavaScript and it adds strict typing to JavaScript and lots of other cool features too like decorators, interfaces and lots more, you can learn about TypeScript by checking their documentation, here's a link to that. Anyways back to webpack, lets install the following dependencies that's gonna help us to the compilation, type npm i typescript ts-loader --save-dev and hit enter and it installs those modules for us. next thing is to open up our webpack.config.js and make some changes to it, we will be replacing the rules for the babel-loader with that for TypeScript just in case things start looking different;



//webpack.config.js
const path = require('path')

module.exports = {
    //new addition
    entry: './src/index.ts',

    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            //new addition
            {
                test: /\.ts$/i,
                exclude : /node_modules/,
                use: 'ts-loader'
            }
        ]
    }
}

Enter fullscreen mode Exit fullscreen mode

Let's create an index.ts file where we will write just a tiny bit of TypeScript;

./index.ts

let HeroName: string = 'deadpool'
console.log(HeroName)

Enter fullscreen mode Exit fullscreen mode

Our directory structure should now look like this;


bundle-app----------------------package.json
                |-------------package.lock.json
                |
                |-------------dist/---------index.html
                |           
                |
                |-------------src/---------index.js
                |                   |------hero.js
                |                   |------style.scss
                |                   |------image.png
                |                   |------index.ts
                |
                |
                |-------------webpack.config.js

Enter fullscreen mode Exit fullscreen mode

Hit npx webpack on the command line to compile the file and if you are done and everything works out fine you should see deadpool logged to the console. That is for our brief introduction to Webpack, if you wanna learn more about webpack and what you can do with it which i highly suggest that you do, you should check out their documentary, thank you and do have a wonderful day.

Top comments (0)