DEV Community 👩‍💻👨‍💻

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

Posted on • Updated on

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

.NET 6 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 ASP.NET’s form validation since it still depends 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 DLLs 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 6 SDK. .NET 5 and .NET Core 2 and 3 will work fine as well. I'm using 6.0.101 and have previously used .NET 5 as well as .NET Core for this setup.
  • NodeJS with bundled npm (or yarn), I’m using 16.14.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

Check the output (or Properties/launchSettings.json) to see which port number has been generated for your project and navigate to localhost to have a look.

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

Front-end dependencies

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

{
    "name": "Net6NpmWebpack",
    "description": "ASP.NET Core MVC project with npm and webpack front-end configuration.",
    "repository": "https://gitlab.com/kdg-ti/integratieproject-1/guides/net6npmwebpack",
    "license": "MIT",
    "version": "4.0.0",
    "dependencies": {
        "@popperjs/core": "^2.11.2",
        "jquery": "^3.6.0",
        "jquery-validation": "^1.19.3",
        "jquery-validation-unobtrusive": "^3.2.12",
        "bootstrap": "^5.1.3"
    },
    "devDependencies": {
        "webpack": "^5.70.0",
        "webpack-cli": "^4.9.2",
        "css-loader": "^6.7.1",
        "style-loader": "^3.3.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 to an existing project.

Apart from the obvious fields we’re specifying:

  • dependencies: includes Bootstrap 5, JQuery, and Popper (for popup placement, used by Bootstrap)
  • 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 inside 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 load 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 the contents of both wwwroot/css/site.css and Views/Shared/_Layout.cshtml.css to ClientApp/src/css. Like so:

ClientApp/
├── package-lock.json
├── package.json
└── src
    ├── css
    │   └── site.css  # contents of wwwroot/css/site.css and Views/Shared/_Layout.cshtml.css
    └── js
        └── site.js   # newly created
Enter fullscreen mode Exit fullscreen mode

Cleanup is important so take your time remove directories wwwroot/css and wwwroot/js entirely and to remove Views/Shared/_Layout.cshtml.css as well.

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: Popper, Bootstrap & JQuery
import '@popperjs/core';
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, Popper, 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|woff(2)?|ttf|otf|svg)$/i,
                type: 'asset'
            },
        ]
    }
};
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] placeholder 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 import 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"] - net6npmwebpack</title>
+    <script 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" asp-append-version="true" />
-    <link rel="stylesheet" href="~/net6npmwebpack.styles.css" asp-append-version="true" />
 </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-fluid">
                 <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">net6npmwebpack</a>
                 <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-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; 2022 - net6npmwebpack - <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

defer 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 localhost (check that port again) 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 Net6NpmWebpack.

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.

Top comments (8)

Collapse
wokle profile image
AslamHamdi

Im trying to import vue in entry.js. Then, when I try to use vue in other page, it shows Vue is not defined. But when I use cdn link and put it in layout.cshtml, it worked.

Collapse
larswillemsens profile image
Lars Willemsens Author

Which bundles and pages do you have? If Vue is only imported for a single bundle then it won't be available on other pages that don't use this bundle.

Collapse
wokle profile image
AslamHamdi

Sorry. I'm new to node js. But here is what I did:

  1. I create an asp.net core MVC apps
  2. Then, I did exactly like the instruction in the post.
  3. I download vue and lodash using npm
  4. Then I import vue and lodash in entry.js and run 'npm run build'
  5. I create a page that share the same layout, _Layout.cshtml which share the same script site.entry.js

As for lodash, it worked fine. But for Vue, when I create a vue app in the other page it said Vue is not defined. But if I create a vue app in layout page and write the js code in site.js it worked.

Thread Thread
larswillemsens profile image
Lars Willemsens Author

So you have site.entry.js, which is loaded from two different pages, but only on one page it throws an error?

Thread Thread
wokle profile image
AslamHamdi

Yes. I loaded site.entry.js in _Layout.cshtml. I create new page which render in _Layout.cshtml . This new page throws an error.

Collapse
paulo673 profile image
Paulo Barbosa

This is great content about asp.net with webpack. Thanks for taking the time to contribute to the growth of many devs

Collapse
benhumphrys profile image
Ben Humphrys

Great article - thanks so much!

Collapse
jakobmatias profile image
Jakob M. Melbye

Thank you very much - this was very helpful! :)

Head to your account's Settings to...

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content