Skip to main content

ASP.NET Core 2.2 with LibMan, NPM and Webpack 4

Javascript tooling is a mess. Every time that I start a new application, I'm always asking myself how I need to setup my tooling. Thankfully, there is a sane way of setting up your tooling that won't make you want to pull your hair out once you set it up. We'll explore how to setup tooling for using NPM modules in your ASP.NET Core [2.2] applications with LibMan and Webpack 4.

Gear and wrench logo (credit to https://www.iconfinder.com/icons/469545/cog_engineering_gear_options_repair_setting_wrench_icon)
Modern logo of tooling

The example will be simple, but sufficient, in order for you to add your complexity that is needed for your application.

Source code

For those that came for just the source code, you can find that right here.

Overview

We are building a tooling pipeline that will take NPM modules, and use webpack to bundle them. Using LibMan, we will move them into the correct directory so our ASP.NET Core application can serve them.

An overview of the tooling chain we are building
An overview of our process we are building

Installation

We will be making use of webpack, LibMan and the NPM Task Runner explorer to make all these pieces fit together. Before we begin, make sure you have these things installed:
  1. Node.js (NPM comes packaged with node)
  2. Visual Studio 2017 v15.8 or later (with the ASP.NET and web development workload) (How might I do this?)
  3. .NET Core 2.1 SDK or later (you can find it here)
  4. Install the NPM Task Runner explorer
  5. In the ASP.NET Core project you want to set up tooling for, run this in your Package Manager Console (You can find this window by going into Tools > NuGet Package Manager > Package Manager Console)
    dotnet tool install -g Microsoft.Web.LibraryManager.Cli

Setup your application

First, add your package.json file to your application. Right click your project and select Add > New Item. Choose Web > Scripts and select the npm Configuration File and click Add.

Adding a package.json file to an application
Adding a package.json file

Feel free to copy paste the following code and replace the contents of your package.json file you just added. The important pieces in this package.json file are the scripts as well as the devDependencies. If you have an existing package.json, make the necessary modifications to your existing file.
{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "scripts": {
    "clean": "node ./clean.js",
    "libman": "libman clean && libman restore",
    "webpack": "webpack ./wwwroot/js/site.js --output ./wwwroot/dist/js/site.min.js --mode=development",
    "build": "npm run clean && npm run webpack",
    "postinstall": "npm run libman"
  },
  "dependencies": {
    
  },
  "devDependencies": {
    "fs": "0.0.2",
    "webpack": "4.29.0",
    "webpack-cli": "3.2.1"
  }
}

Create a clean.js file in your root project directory and replace its contents with the code below. This code will delete the dist files that are used by your application (when bundling your js and css with webpack).
// Cleans the output [distribution] files
var fs = require("fs");
var filesToClean = ["./wwwroot/dist/js/site.min.js"];

for (var i = 0; i < filesToClean.length; i++) {
    if (fs.existsSync(filesToClean[i])) {
        fs.unlinkSync(filesToClean[i]);
    }
}

Create a dist folder and two sub-folders, one for js files and one for css files. The reason we are making a dist folder in wwwroot is so your files are available to the application to use as well as making cleaning dist files simpler.

Creating a dist folder in the Solution Explorer
Creating the dist folder

Create your libman.json file by running this in a command prompt. libman init. You don't need to modify anything when it prompts you for a DefaultProvider.


Running libman init in Powershell

Process

In your day-to-day coding, you'll have some NPM modules you want to use in your application. The first step is adding them to your package.json file. I'll add a module I have published as a sample.

Adding an NPM module to the package.json file
Adding an npm module

Next, run npm install to install said dependency, OR - you can right-click the package.json file in the Solution Explorer and click Restore Packages.

In order to actually use the npm module however, we need to include it's source code in our application. This is done today by bundling our js / related assets with webpack. A npm module can't be loaded on the web by itself, and that is where webpack fills the gap. 

This is a very rudimentary example, but to show how this works, go into site.js and add a require call to our dependency we just installed.
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your Javascript code.
var minify = require("gulp-cshtml-minify");

// Use minify in some way..

Now, if we were to bundle our application with the webpack task (npm run webpack), we should get all the dependencies filled, but we don't because the npm module source code isn't in the wwwroot folder. While we could configure ASP.NET to look in the node_modules folder for our source, what we really want to be doing is moving the NPM module's source code into the wwwroot directory. For that, we need to manually edit the libman.json file. (Additional information can be found here for your future reference).
{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
    {
      "provider": "filesystem",
      "library": "node_modules/gulp-cshtml-minify/",
      "files": [ "index.js" ],
      "destination": "wwwroot/lib/gulp-cshtml-minify/"
    }
  ]
}

And then run the libman task. (To open up the Task Runner explorer, go into View > Other Windows > Task Runner explorer).

Running the libman task in the Task Runner explorer
Running the libman task

Tip - how do we know we need to copy the index.js file from the NPM package? In each NPM package, a root file is defined in the package itself that acts as an entry point into the module. Most NPM modules use index.js, but to check would be to look at the source repo OR look for an index.js in the Solution Explorer.


Looking for source files in the Solution Explorer
Looking for that source file

Once libman is run, we see our NPM module source code in the lib folder.

NPM module source file
NPM module source file!

All we simply need to do now is run the build task whenever we make changes to our main js file, and webpack will bundle everything properly into our dist js file.

Running the build task in the Task Runner explorer
Running the build task

We are all set now! But be sure to change references to load the dist js file instead of the default wwwroot/js/site.min.js if using a ASP.NET web application template in your views/pages!

Improvements

There is obvious room for improvement in this process, but it is a start. Here are some of my own ideas, I'd be interested to know how you feel this could be improved.
  1. Instead of running libman after installing NPM modules, create a node script that can modify/add the appropriate entry (index.js) file of a NPM module that's included in the package.json file.
  2. Update clean.js so that you can remove all files within a given folder, instead of an array of files, or both.
  3. Ensure that libraries that are moved to the /lib folder are not included in the project build, opting to only include the dist/ files.
  4. Add default build commands for css files, and optionally other webpack options.

Comments

  1. i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    i am ERIC BRUNT by name. Greetings to every one that is reading this testimony. I have been rejected by my wife after three(3) years of marriage just because another Man had a spell on her and she left me and the kid to suffer. one day when i was reading through the web, i saw a post on how this spell caster on this address AKHERETEMPLE@gmail.com have help a woman to get back her husband and i gave him a reply to his address and he told me that a man had a spell on my wife and he told me that he will help me and after 3 days that i will have my wife back. i believed him and today i am glad to let you all know that this spell caster have the power to bring lovers back. because i am now happy with my wife. Thanks for helping me Dr Akhere contact him on email: AKHERETEMPLE@gmail.com
    or
    call/whatsapp:+2349057261346










    ReplyDelete








  2. i couldn't believe that i would ever be re-unite with my ex-lover, i was so traumatize staying all alone with no body to stay by me and to be with me, but i was so lucky one certain day to meet this powerful spell caster Dr Akhere,after telling him about my situation he did everything humanly possible to see that my lover come back to me,indeed after casting the spell my ex-lover came back to me less than 48 hours,my ex-lover came back begging me that he will never leave me again,3 months later we got engaged and married,if you are having this same situation just contact Dr Akhere on his email: AKHERETEMPLE@gmail.com thanks very much sir for restoring my ex-lover back to me,his email: AKHERETEMPLE@gmail.com or call/whatsapp:+2349057261346
























    hindi ako makapaniwala na kailanman ay muling makiisa ako sa aking kasintahan, labis akong na-trauma sa pananatiling nag-iisa na walang katawan na manatili sa akin at makakasama ko, ngunit napakasuwerte ako sa isang tiyak na araw upang matugunan ito malakas na spell caster na si Dr Akhere, matapos sabihin sa kanya ang tungkol sa aking sitwasyon ginawa niya ang lahat ng makataong posible upang makita na ang aking kasintahan ay bumalik sa akin, sa katunayan matapos na ihagis ang spell ang aking dating kasintahan ay bumalik sa akin ng mas mababa sa 48 oras, dumating ang dating kasintahan ko. bumalik sa pagmamakaawa sa akin na hindi na niya ako pababayaan, 3 buwan mamaya kami ay nakipag-ugnay at nag-asawa, kung nagkakaroon ka ng parehong sitwasyong ito makipag-ugnay lamang kay Dr Akhere sa kanyang email: AKHERETEMPLE@gmail.com maraming salamat sa sir sa pagpapanumbalik ng aking dating kasintahan bumalik sa akin, ang kanyang email: AKHERETEMPLE@gmail.com o tumawag / whatsapp: +2349057261346

    ReplyDelete
  3. AM SANDRA FROM CANADA, THANKS TO DR ONIHA WHO HELP ME BRING MY HUSBAND BACK, MY HUSBAND LEFT ME WITH THREE KIDS, FOR ANOTHER YOUNG GIRL, FOR OVER TWO YEARS, I TRIED ALL I COULD TO SETTLED OUR DIFFRENCES, BUT IT YIELDED NO RESULT, I WAS THE ONE TAKING CARE OF THE CHILDREN ALONE, UNTIL ONE DAY, I CAME IN CONTACT WITH SOME ARTICLES ONLINE, CONTAINING HOW DR ONIHA HAS HELP SO MANY LOVERS AND FAMILY REUNION AND REUNIT AGAIN, AND I DECIDED TO CONTACT HIM, AND HE CAST HIS SPELL ON MY HUSBAND, WITHIN FIVE DAYS, MY HUSBAND RAN BACK HOME, AND WAS BEGGING ME AND THE KIDS FOR FORGIVENESS, IN CASE YOU ARE PASSING THROUGH SIMILAR PROBLEMS, AND YOU WANTS TO CONTACT DR ONIHA, YOU CAN REACH HIM VIA HIS CONTACT NUMBER, ON CALL OR WHATSAP +2347089275769 OR EMAIL DRONIHASPELL@YAHOO.COM

    ReplyDelete
  4. I was diagnosed as HEPATITIS B carrier in 2013 with fibrosis of the
    liver already present. I started on antiviral medications which
    reduced the viral load initially. After a couple of years the virus
    became resistant. I started on HEPATITIS B Herbal treatment from
    ULTIMATE LIFE CLINIC (www.ultimatelifeclinic.com) in March, 2020. Their
    treatment totally reversed the virus. I did another blood test after
    the 6 months long treatment and tested negative to the virus. Amazing
    treatment! This treatment is a breakthrough for all HBV carriers.

    ReplyDelete
  5. あなたのブログは、常に素晴らしい情報源とインスピレーションの源です。 連続ヒット測定という楽しいゲームを紹介したいと思います。これは、手と目の協調と反応を改善するのに役立ちます 時間。 誰でも遊べるシンプルだけど難しいゲームです。

    ReplyDelete
  6. Good herbal medicine for herpes simplex virus..

    It's a miracle product..

    Works Fast in 14 days,

    I am cured from herpes simplex,

    Email Robinsonbuckler11@gmail.com

    ReplyDelete
  7. Me voy de esta página con un sentido renovado de esperanza y positividad, ¡listo para difundir las buenas vibraciones a mi alrededor! ¡Impresionante cómo un simple clics por segundo puede ser tan divertido y ayudar a mejorar tus habilidades cognitivas al mismo tiempo!

    ReplyDelete

Post a Comment

Popular posts from this blog

UI redesigns are mostly a waste of time

To preface the article, I primarily work on, and prefer, back-end code. I've been involved in both web and software development for over 4 years now and worked with many front-end and back-end frameworks. New Twitter UI Before all of the UI designers that read this go out and riot and champion against me for saying UI redesigns are a waste of time, let me say that I do value design . I think at the bare minimum, a product or website needs to be usable , and if you possess a good eye and steady hand , you should feel compelled to create something that looks pleasing. David Just stop redesigning the UI all the time . UI redesigns, in my opinion, are a waste of time 95% of the time. Let me explain further. No one cares Come see our fresh new look ! What about our new  material design , come see! I'm sorry, but besides fixing the UI where it impacts the usability of your application, no one is raving about how a redesign makes the application any better.

[Fix] - ASUS PCE-AC68 adapter (no internet)

There seem to be a lot of problems with this adapter, even with such strong performance . Why so many issues? I'm not quite sure, but I needed to find a fix because I kept on losing wifi. The ASUS PCE-AC68 The fix Keeping it short - this is how I fixed the issue: Downloaded the driver for my OS from ASUS's support page -  https://www.asus.com/us/Networking/PCEAC68/HelpDesk_Download/ (in my case it was Windows 10 64-bit). Open Device Manager by holding the Windows key and pressing R, then typing "devmgmt.msc" and hitting Enter. (Don't worry, this isn't a scam . We are simply opening Window's Device Manager through the Microsoft Management Console snap-in .) Navigate to the yellow warning sign sitting under Network adapters and right click it. Select Update driver . Select Browse my computer for driver software  and choose the following path of the OS that you have installed on your computer. (The path for the driver on my computer was C

Logging into a website with Powershell

Powershell is great, and it's lately been my go-to shell while I'm working on Windows. Sorry command prompt I really don't do a lot of work in the shell, but I do like to play with low-level interfaces from time to time. The article is about Linux shells, but goes into good explanation about what a shell is if you don't know. Log into a website Today, I wanted to do something that I have never really tried before and that is logging into a website using Powershell . The concepts behind this are quite simple really, as Powershell has support to send HTTP requests  and that's usually all we need, unless the server has CSRF protections in place (which it should). We are going to attempt  to log in to my favorite website for buying socks, Absolute Socks : Is that a turkey?! In order to do that, we need to have a login. So if you don't already have an account on www.absolutesocks.com , go make one now. Viewing the login request On websites,