Rants and Raves

Thanks for visiting my blog!

Using UseStaticFiles with NPM Client Dependencies - Talk Me Out of It
Using UseStaticFiles with NPM Client Dependencies - Talk Me Out of It
March 28, 2018

Ok, please tell me how stupid this is. It’s apt to be pretty stupid but I have a point to it. I’m trying to separate the ideas of prototyping quickly from preparing for production.

I’ve been using Bower to do examples of client-side dependencies. Bower is depreciated so for new dev, I don’t want to recommend it (and VS2017 has removed it too). Bower is clean as you don’t have to introduce a bunch of ideas like gulp or npm scripts to get someone with a working example quickly (Bower’s .rc file let’s you tell it where to put the dependencies). I want to do the same thing with NPM.

Here is the idea. Instead of writing a script or using gulp to move the files, I’m thinking of using UseStaticFiles to just allow node_modules directory to be available to client-side development. My expectation is that this is a development-only idea and will allow you to get up to speed quickly. But when you’re ready to deploy, you’ll need to do the harder work of writing a NPM script to copy only the files you really need.

Here’s how it works. You add a new piece of StaticFiles middleware pointing to the node_modules directory so you never have to copy it to wwwroot. For example:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  // ...

  app.UseStaticFiles();
  if (env.IsDevelopment)
  {
    app.UseStaticFiles(new StaticFileOptions()
    {
      RequestPath = PathString.FromUriComponent("/libs"),
      FileProvider = new PhysicalFileProvider(
          Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
    });
  }

  // ...
    
}

This way in Development, I can use the libs directory as an alias for node_modules to get up to speed quickly:

    <environment include="Development">
        <script src="~/libs/jquery/dist/jquery.js"></script>
        <script src="~/libs/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>

Who hates this idea?