MD Bootstrap Webpack tutorial

Topic: MD Bootstrap Webpack tutorial
Published 02.01.2019 Updated 03.12.2019

Arnt Oddvar Pedersen pro posted 4 years ago

This tutorial is created by Arnt Oddvar Pedersen and published thanks to his contribution.

Check out his profile page and Github.

You can find this entire tutorial complete and ready for use, in this GitHub repository.


Getting Started 

Welcome to this quick guide where you'll learn how to setup a complete Webpack environment optimized and ready for both Development and Production use. 

First and foremost, you will need NodeJS installed on your Mac/Computer. 

You can download NodeJS from here. 

I also highly recommend using Visual Studio Code as your Code Editor. This is also my preferred code editor personally. 


Once NodeJS is done installing on your system, create a folder where you want to start your project, open a command line, navigate to your newly created folder and initialize the project using the following command:

npm init

You'll then be asked a series of questions about your project. How you answer them is up to you.


Installing required packages 

Now that you've initialized your project, it's time to start adding the packages that we need for an automated production and development environment. 

To make full use of how powerful JavaScript has become in recent years, for this tutorial we're going to install Babel with a few plugins that transpiles edge JS to plain simple ES5. 

We are also going to install ESLint and the AirBnB JavaScript style guide to automatically find (and automatically fix some) problematic patterns of code while making sure we are adhering to a true-and-tested, mostly reasonable approach to JavaScript. 

Finally, we’re also going to install Webpack to manage our project. In your command line, run the following command to install all the needed "devDependencies" we need to manage our tutorial project.

npm install --save-dev @babel/cli @babel/core @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators @babel/plugin-proposal-do-expressions @babel/plugin-proposal-export-default-from @babel/plugin-proposal-export-namespace-from @babel/plugin-proposal-function-bind @babel/plugin-proposal-function-sent @babel/plugin-proposal-json-strings @babel/plugin-proposal-logical-assignment-operators @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-numeric-separator @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-pipeline-operator @babel/plugin-proposal-throw-expressions @babel/plugin-syntax-dynamic-import @babel/plugin-syntax-import-meta @babel/plugin-transform-arrow-functions @babel/preset-env babel-eslint babel-loader clean-webpack-plugin copy-webpack-plugin css-loader eslint eslint-config-airbnb-base eslint-loader eslint-plugin-import file-loader html-loader html-webpack-plugin mini-css-extract-plugin node-sass optimize-css-assets-webpack-plugin sass-loader style-loader terser terser-webpack-plugin webpack webpack-cli webpack-dev-server

This operation might some time, so sit back and enjoy a cup of coffee or tea while you wait.


Finally, to make MDBootstrap for jQuery work properly, we also need to install some required dependencies that MDB require to operate. (Both Free & Pro) 

In your terminal/command line, paste the following command:

npm install --save @fortawesome/fontawesome-free bootstrap es6-promise hammerjs jquery node-waves popper.js underscore wow.js

Since Webpack can’t automatically detect the bundled modules of the MDBootstrap main JavaScript file, we need to install the required modules as dependencies. Once we’re done, Webpack will make sure that we’re not including duplicate modules when we are packing and bundling all our modules and JavaScript files for production use.


Configure ESLint 

In your root project folder, create a file called .eslintrc and paste the following code into it, then save it. 

<span data-ccp-props="{"201341983":0,"335559739":160,"335559740":259}">{<br />  "extends": "airbnb-base",<br />  "parser": "babel-eslint",<br />  "env": {<br />    "browser": true,<br />    "jquery": true<br />  }<br />}<br /></span>


Configure Babel 

In your root project folder, create a file called .babelrc and paste the following code into it, then save it. 

{<br />  "presets": ["@babel/preset-env"],<br />  "plugins": [<br />    "@babel/plugin-proposal-class-properties",<br />    ["@babel/plugin-proposal-decorators", { "decoratorsBeforeExport": true }],<br />    "@babel/plugin-proposal-do-expressions",<br />    "@babel/plugin-proposal-export-default-from",<br />    "@babel/plugin-proposal-export-namespace-from",<br />    "@babel/plugin-proposal-function-bind",<br />    "@babel/plugin-proposal-function-sent",<br />    "@babel/plugin-proposal-json-strings",<br />    "@babel/plugin-proposal-logical-assignment-operators",<br />    "@babel/plugin-proposal-nullish-coalescing-operator",<br />    "@babel/plugin-proposal-numeric-separator",<br />    "@babel/plugin-proposal-optional-chaining",<br />    ["@babel/plugin-proposal-pipeline-operator", { "proposal": "minimal" }],<br />    "@babel/plugin-proposal-throw-expressions",<br />    "@babel/plugin-syntax-dynamic-import",<br />    "@babel/plugin-syntax-import-meta",<br />    "@babel/plugin-transform-arrow-functions",<br />  ],<br />}


Wrapping up, configuring Webpack

Wrapping up, configuring Webpack 

Now that we’ve setup the entire project and installed the packages we need, it’s finally time to wrap-up this tutorial. Create a file in your project root folder called webpack.config.js 

This configuration file instructs Webpack how to handle all the file-types in your project/web-app, how to serve them for both production and development environments and WHERE to find your source files. A little bit of JavaScript knowledge here will go a long way, but I will try and explain everything as well. 

Before we start, you’ll see the following string mentioned a few times in the configuration file: path.resolve(__dirname, ‘folder1’, ‘subfolder’, ‘subfolder’) 

What this does, combined with “__dirname” gives you the absolute path to the directory containing the source file which is being executed (in node). When you add a comma separated list of folders afterwards, it tries to resolve and return the entire path, for example: 



Now, paste the following into your webpack.config.js: 


const path = require('path');<br />const webpack = require('webpack');<br />const TerserPlugin = require('terser-webpack-plugin');<br />const CopyWebpackPlugin = require('copy-webpack-plugin');<br />const HtmlWebPackPlugin = require('html-webpack-plugin');<br />const CleanWebpackPlugin = require('clean-webpack-plugin');<br />const MiniCssExtractPlugin = require('mini-css-extract-plugin');<br />const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');<br /><br />module.exports = (env, argv) => {<br />return {<br />entry: [],<br />output: {<br />path: path.resolve(__dirname, 'dist'),<br />filename: 'bundle.js',<br />},<br />mode: argv.mode,<br />module: {<br />rules: [<br />{<br />enforce: 'pre',<br />test: /\.js$/,<br />exclude: /(node_modules|bower_components|vendors)/,<br />loader: 'eslint-loader',<br />options: {<br />fix: true,<br />},<br />},<br />{<br />test: /\.js$/,<br />exclude: /(node_modules|bower_components|vendors)/,<br />loader: 'babel-loader',<br />options: {<br />cacheDirectory: true,<br />},<br />},<br />{<br />test: /\.html$/,<br />loader: 'html-loader',<br />options: {<br />minimize: true,<br />removeComments: true,<br />collapseWhitespace: true,<br />},<br />},<br />{<br />test: /\.(sa|sc)ss$/,<br />use: [argv.mode !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],<br />},<br />{<br />test: /\.(jpe?g|png|gif)$/,<br />loader: 'file-loader',<br />options: {<br />outputPath: 'assets/',<br />},<br />},<br />{<br />test: /\.(eot|svg|ttf|woff2?|otf)$/,<br />loader: 'file-loader',<br />options: {<br />outputPath: 'assets/',<br />},<br />},<br />],<br />},<br />plugins: [<br />new HtmlWebPackPlugin({<br />template: './src/index.html',<br />filename: 'index.html',<br />}),<br />new webpack.ProvidePlugin({<br />$: 'jquery',<br />jQuery: 'jquery',<br />'window.$': 'jquery',<br />'window.jQuery': 'jquery',<br />Waves: 'node-waves',<br />_: 'underscore',<br />Promise: 'es6-promise',<br />}),<br />new MiniCssExtractPlugin({<br />filename: argv.mode !== 'production' ? '[name].css' : '[name].[hash].css',<br />chunkFilename: argv.mode !== 'production' ? '[id].css' : '[id].[hash].css',<br />cssProcessorOptions: {<br />safe: true,<br />discardComments: {<br />removeAll: true,<br />},<br />},<br />}),<br />new CopyWebpackPlugin([<br />{<br />from: '**/*',<br />to: 'mdb-addons',<br />context: path.resolve(__dirname, 'src', 'vendors', 'mdb', 'mdb-addons'),<br />},<br />]),<br />new CleanWebpackPlugin('dist', { verbose: true }),<br />],<br />optimization: {<br />splitChunks: {<br />chunks: 'all',<br />},<br />minimizer: [<br />new TerserPlugin({<br />parallel: true,<br />sourceMap: true,<br />terserOptions: {<br />output: {<br />comments: false,<br />},<br />},<br />}),<br />new OptimizeCSSAssetsPlugin({}),<br />],<br />},<br />performance: {<br />hints: false,<br />},<br />};<br />};

(I have no idea why this won't format correctly...)

Before you can sit back and enjoy, thinking this tutorial is over – there are a few things we need to do.   

You’ll notice that the entry object is empty. This takes a string or array of strings with your app's entry-points. Place your main JavaScript and SCSS/SASS file that references all other files here.  

Next is the output object. Here you’ll need to set your desired path, where all the files will be put once you build your project for production. You’ll notice I’ve already set the output path to create a folder called dist in your project root. Next, you’ll see the filename variable. I’ve pre-set this to compile all JavaScript files into a file called bundle.js. Feel free to change the filename as well if you want.  

Note: All files will be served from the output path that is set in this object.  


Moving along, you’ll see the module object. This instructs Webpack what to do with the different file-types. Towards the bottom you’ll see the sections for images and web-font files. Here, you can set the output path to whatever you want. Once Webpack comes across these kinds of files, it will put the files Webpack finds into the folder name (or path) you type in here. I’ve already set the path here to put all image and font files into its own assets folder. If you want to separate these files into their own folders or want another destination folder, feel free to change the outputPath for both images and web-fonts.  

Finally, we come to the plugins object. This object further details how handle specific files or ranges of files. The first function you will come across is how we instruct Webpack about our HTML files. I’ve already set the first one for you, instruction Webpack where the template for our index.html file can be found, as well as what to call our first HTML file. The filename string can contain a path+name of the HTML file or simply the name.   

For example, if I wanted my index.html to be in its own folder, I would set the filename string to: my/directory/index.html and Webpack would try to resolve or create the path where you want your index.html file to reside. For simplicity sake, I’ve set Webpack to just dump the index.html file into our output folder. You can read more about the HTML Webpack Plugins’ settings here.  

Special note: There are many neat things you can do with this plugin. Keep an eye out on the Github repository link at the top for an advanced example coming soon.  


Next is the CSS extraction plugin. After Webpack is done processing any SCSS/SASS files in your project and converted them to CSS, this plugin tells Webpack what to do with the css files in production mode. Like above, if you want your CSS files to go into a separate directory, include the path in the filename and chunkFilename for both sets.  

The final two plugins are negligible. CopyWebpackPlugin copies the mdb-addons folder from the MDB Pro version if it exists. Since I store all my source files within a src/ folder, change the context path here to point to where you have your mdb-addons folder if you’re using the Pro version. Free users can just ignore this path.  

CleanWebpackPlugin simply deletes the dist folder every time you build your project.  


The optimization object is something you can play around with. I’ve sat the settings I personally use for production mode, splitting large css/js files into multiple smaller files (chunks), and minimizes your JavaScript files, using all your CPU cores for maximum speed, while removing all comments.  

Since some libraries needed by MDB and MDB itself, hints have been turned off to ignore warnings about large file sizes possibly having an impact on web load speeds.  


Congratulation on setting up Webpack for MDB and getting ready to develop! To see a full working example, check/clone my GitHub repository linked at the top of this tutorial.  

I am constantly updating this guide and the repository, so keep an eye out for changes. Feedback, criticism and comments are also welcome!  

For any problems, feel free to use the issue tracker on my GitHub repository and I’ll help you out as soon as I can.  

Thank you!  


TeddyS31 pro commented 3 years ago

This may seem like a pain but it would be wonderful if there were a video to go along with this tutorial and a little more explanation on your extra files you have in your GitHub repo. But otherwise awesome tutorial. 

Arnt Oddvar Pedersen pro commented 3 years ago

Hello Teddy! Thanks for the input. It's no pain at all. I'm working on an updated guide, to reflect changes that came in Webpack 4 and Babel 6+ which made a lot of things easier. I can certainly look into getting a movie made for those that prefer a visual guide instead of a written one.

Oskar Barcz commented 3 years ago

Please make a tutorial section about spinning it up with Webpack Encore please :D

Arnt Oddvar Pedersen pro commented 3 years ago

Thank you for the suggestion, Oskar! I'll include this in the updated guide. :)

dojo44 commented 3 years ago

I assume this has no bearing with Angular 8.  I really need to get this working with Angular 8.  I have the pro version and have a reasonable expectation that ng build --prod would work.

Arnt Oddvar Pedersen pro commented 3 years ago

Setting Webpack + MDBootstrap up for both Angular and React/React Native isn't really that much different. If there is any interest, I could include sections about both React and Angular when I publish my updated guide. :)

mgtripoli pro commented 2 years ago

Do you happen to have the React version yet?

Chase Tran commented 2 years ago

Why aren't the dependencies inside mdbootstrap's package.json?

KES commented 10 months ago

Two years and no update ((

Mikołaj Smoleński staff commented 9 months ago

We prepared a brand new pre-configured Webpack Starter. Please check the guide:

Keep coding, 
Mikołaj from MDB

Please insert min. 20 characters.