DEV Community

loading...
Cover image for Managing ASP.NET Core MVC front-end dependencies with npm and webpack (part 1)

Managing ASP.NET Core MVC front-end dependencies with npm and webpack (part 1)

larswillemsens profile image Lars Willemsens ・9 min read

.NET 5 provides a couple of great project templates to get you up and running quickly. However, the MPA (multiple-page application) is not getting a lot of attention. Packages are outdated and you can’t add new JS libraries using modern practices.
Starting out is easy though: either you choose the web template, which gives you an almost empty project, or you can opt for more boilerplate by choosing the mvc or webapp template.

Both have their (dis)advantages:

  • dotnet new web: this gives you… pretty much nothing. That’s not necessarily a bad thing if you’re up for configuring everything from scratch.
  • dotnet new mvc (or webapp): gives you an MPA right off the bat, but the front-end libraries are outdated and bundled with the project, which doesn’t provide a lot of room for change. (webapp results in a page-based project while mvc produces a Model-View-Controller project)

It can be challenging to get your front-end configured just the way you want, especially when you’re not starting out from the angular or react templates. If you want to do anything related to multiple pages/views or even if you want to use a SPA-framework other than the ones provided (such as Vue or Svelte!) then this guide can help you set that up!

What we’re about to do

  • We’re going to set up an ASP.NET Core MVC project with custom front-end dependencies. It’ll be a multi-page app that is tailored to our needs. More specifically…
  • We’ll be making sure Bootstrap is a dependency of the project instead of a part of the project. So our project tree will no longer be cluttered with a bunch of minified JS and MAP files.
  • We’ll be kicking out JQuery like it’s 2014! It’ll only be referenced from Bootstrap and ASP.NET’s form validation since both still depend on it.
  • The dependencies and build process will be set up using npm and webpack. Any JavaScript and CSS code that we write will be processed by this build task. We’ll move all .js and .css files into a separate src directory. Only the build artifacts will end up in wwwroot.

Why we’re doing it

First and foremost, the MVC template is much too firm and inflexible. Adding new front-end libraries to the project is a bit of an undertaking and that shouldn’t be the case.

Adding a NuGet package to the project (thankfully) doesn’t result in a bunch of DDLs in the project tree. Neither should be the case when adding a library for the front-end. We also want control over the exact version numbers that are used, just like with NuGet packages.

Along the way, we’ll get a better insight into how webpack can be used outside of a SPA!

Let’s get to it!

Creating the project

What you’ll need:

  • A .NET 5 SDK. .NET Core 2 and 3 will work fine as well. I'm using 5.0.104 and have previously used .NET Core for this setup.
  • NodeJS with bundled npm (or yarn), I’m using 14.16.0.
  • Optionally, an IDE. For now, all you need is a functional command line!

Let’s create a new MVC project. Navigate to a new empty directory and enter the following:

$ dotnet new mvc
Enter fullscreen mode Exit fullscreen mode

If you’re using git then go ahead and create a .gitignore file. Thankfully, there's a separate .NET template to take care of this. Still from within your project directory, enter:

$ dotnet new gitignore
Enter fullscreen mode Exit fullscreen mode

Launch the project with:

$ dotnet run
Enter fullscreen mode Exit fullscreen mode

… and navigate to https://localhost:5001 to have a look.

This startup project can be found on Gitlab as the first version of NetCoreNpmWebpack.

Front-end dependencies

Next up, create a new directory called ClientApp at the root of your MVC project. Within this new directory, create a file called package.json. Give it the following content:

{
    "name": "NetCoreNpmWebpack",
    "description": "ASP.NET Core MVC project with npm and webpack front-end configuration.",
    "repository": "https://gitlab.com/kdg-ti/integratieproject-1/guides/netcorenpmwebpack",
    "license": "MIT",
    "version": "3.0.0",
    "dependencies": {
        "jquery": "^3.6.0",
        "jquery-validation": "^1.19.3",
        "jquery-validation-unobtrusive": "^3.2.12",
        "bootstrap": "^4.6.0",
        "popper.js": "^1.16.1"
    },
    "devDependencies": {
        "webpack": "^5.31.0",
        "webpack-cli": "^4.6.0",
        "css-loader": "^5.2.0",
        "style-loader": "^2.0.0",
        "file-loader": "^6.2.0",
        "url-loader": "^4.1.1"
    },
    "scripts": {
        "build": "webpack"
    }
}
Enter fullscreen mode Exit fullscreen mode

You’ll want to change the values of the first five fields in case you’re applying these steps on an existing project.

Apart from the obvious fields we’re specifying:

  • dependencies: includes Bootstrap 4 and JQuery
  • devDependencies: webpack and webpack-related loaders. We’ll need these to bundle our front- end code.
  • scripts: a single command that invokes the webpack bundling process

Go ahead and run the following command from within the ClientApp directory:

$ npm install
Enter fullscreen mode Exit fullscreen mode

A new node_modules directory will have popped up containing a massive amount of JS and CSS files. Consider this directory to be like the bin and obj directories (or better yet, the NuGet package cache). Although it doesn’t contain any binaries, its content is still a number of dependencies that we refer to from within our own code.

… but we don’t have any code yet. Let’s add some by creating a src directory inside ClientApp and adding both a js and a css directory at that location. Create a new file called site.js in the js directory and move site.css from wwwroot/css to ClientApp/src/css. Like so:

ClientApp/
├── package-lock.json
├── package.json
└── src
    ├── css
    │   └── site.css       # moved from wwwroot/css
    └── js
        └── site.js        # newly created
Enter fullscreen mode Exit fullscreen mode

Cleanup is important so take your time remove wwwroot/css and wwwroot/js entirely.

In site.js we will write custom JavaScript code that’s relevant to the entire site. Additionally, we'll use this file to import all site-wide dependencies:

// JS Dependencies: Bootstrap & JQuery
import 'bootstrap';
import 'jquery';
// Using the next two lines is like including partial view _ValidationScriptsPartial.cshtml
import 'jquery-validation';
import 'jquery-validation-unobtrusive';

// CSS Dependencies: Bootstrap
import 'bootstrap/dist/css/bootstrap.css';

// Custom JS imports
// ... none at the moment

// Custom CSS imports
import '../css/site.css';

console.log('The \'site\' bundle has been loaded!');
Enter fullscreen mode Exit fullscreen mode

Lines 2 to 9 will import code from within node_modules. We’re importing Bootstrap’s Javascript and CSS as well as a couple of JQuery libaries that are used by ASP.NET Core’s validation scripts.
All of this is done using ECMAScript 6 modules, a modern approach to importing JS files from other JS files or even CSS files from JS files.

Now… how can we possibly get this code into a user’s browser? The file that we just created contains only 17 lines of code, but it imports a small list of libraries as well as some custom CSS code. Do we just throw node_modules at our users? Of course not! This directory is so large that we need to carefully filter, bundle and host only those parts that are needed at runtime.

… this is where webpack comes in!

Building the bundle

Create a new file called webpack.config.js and place it in the ClientApp directory. Give it the following content:

const path = require('path');

module.exports = {
    entry: {
        site: './src/js/site.js'
    },
    output: {
        filename: '[name].entry.js',
        path: path.resolve(__dirname, '..', 'wwwroot', 'dist')
    },
    devtool: 'source-map',
    mode: 'development',
    module: {
        rules: [
            { test: /\.css$/, use: ['style-loader', 'css-loader'] },
            { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: ['file-loader'] },
            {
                test: /\.(woff|woff2)$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5000,
                        },
                    },
                ]
            },
            {
                test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10000,
                            mimetype: 'application/octet-stream',
                        },
                    },
                ]
            },
            {
                test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 10000,
                            mimetype: 'image/svg+xml',
                        },
                    },
                ]
            },
        ]
    }
};
Enter fullscreen mode Exit fullscreen mode

Without going into too much detail, we’re specifying that a bundle should be created based on src/js/site.js and that this bundle should be called site.entry.js (the [name] tag is replaced with “site”).

webpack is smart enough to figure out what should be included in the bundle and it bases its decision-making on what we do in site.js. For example, if we use JQuery, then JQuery will be included in the bundle. Even CSS files such as those from Bootstrap will be included in the bundle if we choose to import them from within site.js. (In the rules section at the bottom we specify how those non-JS files are handled.)

Ok, let’s build this using the following command from within the ClientApp directory:

$ npm run build
Enter fullscreen mode Exit fullscreen mode

Basically, this executes the webpack command as can be seen in the scripts section of package.json above.
This build results in two new files:

wwwroot/dist/
├── site.entry.js
└── site.entry.js.map
Enter fullscreen mode Exit fullscreen mode

Now we can include those from within our HTML. Open Views/Shared/_Layout.cshtml and replace all script and link tags (even those at the bottom!) with a single line:

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title>@ViewData["Title"] - NetCoreNpmWebpack</title>
+    <script type="module" src="~/dist/site.entry.js" defer></script>
-    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
-    <link rel="stylesheet" href="~/css/site.css" />
 </head>
 <body>
     <header>
         <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
             <div class="container">
                 <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">NetCoreNpmWebpack</a>
                 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                         aria-expanded="false" aria-label="Toggle navigation">
                     <span class="navbar-toggler-icon"></span>
                 </button>
                 <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                     <ul class="navbar-nav flex-grow-1">
                         <li class="nav-item">
                             <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                         </li>
                         <li class="nav-item">
                             <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                         </li>
                     </ul>
                 </div>
             </div>
         </nav>
     </header>
     <div class="container">
         <main role="main" class="pb-3">
             @RenderBody()
         </main>
     </div>

     <footer class="border-top footer text-muted">
         <div class="container">
             &copy; 2021 - NetCoreNpmWebpack - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
         </div>
     </footer>
-    <script src="~/lib/jquery/dist/jquery.min.js"></script>
-    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
-    <script src="~/js/site.js" asp-append-version="true"></script>
     @await RenderSectionAsync("Scripts", required: false)
 </body>
 </html>
Enter fullscreen mode Exit fullscreen mode

type="module" indicates that this JS file contains “ECMAScript 6 modules” and defer (which is actually the default for such modules) indicates that execution of this file should be delayed until the page is fully loaded. That’s a modern alternative to putting all script tags at the bottom of a document to make sure that the document is fully downloaded before the scripts start scanning the DOM.

Time to delete the last bit of clutter from our project tree:

$ rm -rf wwwroot/lib
Enter fullscreen mode Exit fullscreen mode

If you’re as obsessed with useless comments as I am then now’s the time to remove the top comment in site.css. Whatever minification reference is being made there, we’re not going down that path anyway.
And if you’re using git then make sure to add wwwroot/dist/ to your .gitignore.

Alright, time to check it out!

$ dotnet run
Enter fullscreen mode Exit fullscreen mode

Open https://localhost:5001 in a browser and check the browser console (F12). You should see the message “The ‘site’ bundle has been loaded!”.

How cool is that? All of the front-end’s dependencies are now downloaded, built and bundled dynamically. The build system is extensible and all dependencies are easily managed and replaceable if needed!

The project so far can be found on Gitlab as version 2 of NetCoreNpmWebpack.

What’s next?

We’re not quite finished. There are two important things on our TODO list:

  • Performance! Try switching quickly between different pages in the SPA. You’ll see a delay before Bootstrap’s CSS gets applied. This is caused by a large amount of CSS getting plugged into the page at runtime. This is the most urgent thing to fix, user experience is just too important!
  • Building the project as a whole. At this point building the .NET project doesn’t trigger a rebuild for the front-end. How annoying! :)

In part 2 we’ll be tackling the performance issue and streamlining the build process.

Discussion (0)

pic
Editor guide