Adding Webpack to an MVC Project with JavaScript

Imagine a website built with only HTML, CSS, and JavaScript (JS). As it grows, the JavaScript file that contains its features becomes huge. You start splitting functionality across files and importing each script in a specific order in the HTML.

The project keeps getting bigger, and one small mistake can break the site. It becomes harder and harder to work with.

In this article, we'll look at how Webpack can improve the development workflow and how to use it in a small project I built in this post about the Model View Controller (MVC) architecture.

MVC and Webpack

You can clone the project from GitHub; it already has the structure we'll use to configure Webpack.

What is Webpack?

Webpack is a module bundler. It lets us split code into manageable files without having to import them in a specific order in the HTML. Instead, we import each module where it is used. Webpack bundles everything into a dist folder for the production build 🎉

What will this Webpack project include?

The project will include Babel configuration files. Babel translates modern JavaScript into older JavaScript supported by more browsers, so we can use newer features with less concern about browser compatibility. We'll also use the MVC architecture. Sounds good? Let's configure the project.

Creating webpack.config.js

At the project root, create a file named webpack.config.js. It will contain the settings we need for Webpack. Then install Webpack by running:

npm install webpack webpack-cli webpack-dev-server --save-dev

This command installs three packages:

  • webpack: the bundler itself.
  • webpack-cli: provides commands for configuring and running Webpack.
  • webpack-dev-server: watches code changes during development and reloads the browser.

Back in webpack.config.js, add:

const path = require("path"); module.exports = { entry: "./src/js/index.js", output: { path: path.resolve(__dirname, "dist"), filename: "js/bundle.js", }, devServer: { static: { directory: path.join(__dirname, "src"), }, compress: true, port: 9000, }, }, };

Here's what these settings do:

The entry property tells Webpack where the project starts. Here, it points to index.js, the MVC Controller.

The output property defines where the bundled files will go. The path points to the dist folder, and filename sets the output file to bundle.js inside the js folder.

The devServer property tells Webpack which folder to watch during development. When you save a change, the browser reloads to show it.

Configuring Babel

First, install Babel and its related packages:

npm install @babel/core @babel/preset-env --save-dev
  • @babel/core: contains Babel's core functionality.
  • @babel/preset-env: includes plugins that help transform JavaScript.

Next, install Babel's polyfill, which connects Babel to Webpack:

npm install @babel/polyfill --save

After installing the packages, create a .babelrc file at the project root. It will configure how modern JavaScript is transformed into older JavaScript. Add:

{ "presets": [ ["@babel/preset-env", { "targets": { /* * Suporta as últimas 5 versões de cada navegador e certifica de que * todas as versões do IE (a partir da 8) sejam compatíveis. */ "browsers": [ "last 5 versions", "ie >= 8" ] } }] ] }

The targets property, with its browsers setting, tells Babel to support the latest five versions of each browser and Internet Explorer version 8 and later.

Now open webpack.config.js and add Babel's polyfill to the entry. The file should look like this:

const path = require("path"); module.exports = { entry: ["@babel/polyfill", "./src/js/index.js"], output: { path: path.resolve(__dirname, "dist"), filename: "js/bundle.js", }, devServer: { static: { directory: path.join(__dirname, "src"), }, compress: true, port: 9000, }, };

Installing plugins

Webpack plugins make it easier to optimize development tasks.

First, install html-webpack-plugin. It adds the HTML file to the output folder and includes the bundles and files it uses, such as index.js:

npm install html-webpack-plugin --save-dev

Next, install mini-css-extract-plugin and css-loader:

npm install mini-css-extract-plugin css-loader --save-dev
  • mini-css-extract-plugin: extracts CSS used by JavaScript files into separate CSS files.
  • css-loader: interprets import, url(), and require() in JavaScript files.

Now add the plugins to webpack.config.js:

const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { /*...*/ plugins: [ new HtmlWebpackPlugin({ filename: "index.html", // Arquivo de saída em nossa pasta dist template: path.resolve(__dirname, "./src/index.html"), // Nosso arquivo HTML do projeto }), new MiniCssExtractPlugin({ filename: "css/[name].css", // Arquivo de saída em nossa pasta dist }), ], module: { rules: [ { test: /\.css$/i, use: [MiniCssExtractPlugin.loader, "css-loader"], }, ], }, }

In index.js, import the CSS file:

import "../css/styles.css";

Scripts

Add these scripts to package.json:

"scripts": { "build": "webpack --mode production", // Gera a pasta dist "start": "webpack-dev-server --mode development --open" // Inicia a aplicação para o desenvolvimento },

Now run this command to create the dist folder:

npm run build

Then start the app and open it at http://localhost:9000/:

npm start

The dist folder now contains a bundled HTML file, a css folder with main.css, and a js folder with bundle.js, containing JavaScript features supported by the browsers specified in the Babel configuration.

Conclusion

We've created a simple Webpack 5 configuration, ready for production, with Babel, MVC, production optimization, and a development server. Webpack has many other features, but this can be a starting point. I recommend exploring further—for example, adding SASS alongside the configuration from this post. With this foundation, you can build other applications with a framework or whatever you prefer 🤯😄

Have fun! If you have questions, you can reach me on Twitter 🤗

Buy Me A Coffee

Comentários