Coder Social home page Coder Social logo

shazwazza / smidge Goto Github PK

View Code? Open in Web Editor NEW
363.0 18.0 48.0 2.69 MB

A lightweight runtime CSS/JavaScript file minification, combination, compression & management library for ASP.Net Core

License: MIT License

C# 68.53% CSS 0.04% JavaScript 29.97% HTML 1.45% Less 0.01%
minification compression javascript asp-net-core css hactoberfest

smidge's Introduction

Smidge Build

Smidge Smidge

NuGet

A lightweight runtime CSS/JavaScript file minification, combination, compression & management library for ASP.Net (.NET Standard)


❤️ If you use and like Smidge please consider becoming a GitHub Sponsor ❤️

News

Features

  • Minification, combination, compression for JS/CSS files
  • Properly configured client side caching, persistent server side caching (no rebundling unnecessarily)
  • Fluent syntax for creating and configuring bundles
  • Debug/Production configurations for each bundle
  • Cache busting - and you can customize/replace how it works
  • JS source maps (via the Smidge.Nuglify package)
  • File watchers to auto invalidate/refresh a processed bundle
  • Extensible - you can completely customize the pre-processor pipeline and create your own processors and for any file type

Quick Start

  1. Install from Nuget:
    Install-Package Smidge
    
  2. Add Smidge config to appsettings.json:
    "smidge": {
        "dataFolder" : "Smidge",
        "version" : "1"
      }  
  3. Add smidge to your services:
    services.AddSmidge(Configuration.GetSection("smidge"));
  4. Create a bundle in your configure method:
    app.UseSmidge(bundles =>
    {
       bundles.CreateJs("my-application", "~/js/site.js", "~/js/app");
    });
  5. Add the tag helpers to your _ViewImports.cshtml file:
    @addTagHelper *, Smidge
  6. Render your bundle:
    <script src="my-application"></script>

See Installation for full configuration details

Usage

Pre-defined bundles

Define your bundles during startup:

services.UseSmidge(bundles =>
{
   //Defining using file/folder paths:
   
   bundles.CreateJs("test-bundle-2", "~/Js/Bundle2", "~/Js/OtherFolder/*.js");
   
   //Or defining using JavaScriptFile's or CssFile's
   //this allows you to custom the pipeline per file
   
   bundles.Create("test-bundle-1", //bundle name
      new JavaScriptFile("~/Js/Bundle1/a1.js"),
      new JavaScriptFile("~/Js/Bundle1/a2.js"));
       
   //Then there's all sorts of options for configuring bundles with regards to customizing their pipelines,
   //customizing how rendering is done based on Debug or Production environments, if you want to 
   //enable file watchers, configure custom cache busters or the cache control options, etc...
   //There's even a fluent API to do this! Example: 
   
   bundles.CreateJs("test-bundle-3", "~/Js/Bundle3")
      .WithEnvironmentOptions(BundleEnvironmentOptions.Create()
         .ForDebug(builder => builder
            .EnableCompositeProcessing()
            .EnableFileWatcher()
            .SetCacheBusterType<AppDomainLifetimeCacheBuster>()
            .CacheControlOptions(enableEtag: false, cacheControlMaxAge: 0))
         .Build()
   );
});

If you don't want to create named bundles and just want to declare dependencies individually inside your Views, you can do that too! You can create bundles (named or unnamed) during runtime ... no problem.

See Declarations for full declaration/usage details

Rendering

The easiest way to render bundles is simply by the bundle name:

<script src="my-awesome-js-bundle"></script>
<link rel="stylesheet" href="my-cool-css-bundle"/>

This uses Smidge's custom tag helpers to check if the source is a bundle reference and will output the correct bundle URL. You can combine this with environment variables for debug/non-debug modes. Alternatively, you can also use Razor to do the rendering.

See Rendering for full rendering & debug mode details

Custom pre-processing pipeline

It's easy to customize how your files are processed including the way files are minified, how URLs are resolved, etc.... This can be done at a global/default level, at the bundle level or at an individual file level.

See Custom Pre-Processing Pipeline for information about customizing the pre-process pipeline

URLs

There's a couple of methods you can use to retrieve the URLs that Smidge will generate when rendering the <link> or <script> html tags. This might be handy in case you need to load in these assets manually (i.e. lazy load scripts, etc...):

Task<IEnumerable<string>> SmidgeHelper.GenerateJsUrlsAsync()
Task<IEnumerable<string>> SmidgeHelper.GenerateCssUrlsAsync()

See Asset URLs for information about retrieving the debug and non-debug asset urls for your bundles

Documentation

All of the documentation lives here

I haven't had time to document all of the features and extensibility points just yet but I'm working on it :)

Copyright & Licence

© 2021 by Shannon Deminick

This is free software and is licensed under the MIT License

Logo image Designed by Freepik

smidge's People

Contributors

bergmania avatar craigs100 avatar dazinator avatar dependabot[bot] avatar gunnim avatar jeavon avatar jimbobsquarepants avatar kevinjump avatar markadrake avatar nikcio avatar phyxionnl avatar shazwazza avatar slorion avatar vincentparrett avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

smidge's Issues

CssUrlProcessor Issue

I was just attempting to bundle some css for telerik's Kendo UI, and hit this problem in the CssUrlProcessor

image

An exception is thrown by the Uri contructor:

image

cssLocation is /lib/font-awesome/css/font-awesome.min.css and match is "../fonts/fontawesome-webfont.eot?v=4.5.0"

The exception is an ArgumentOutOfRangeException

Smidge needs to throw if duplicate bunlde names are used for different bundle types

Hello! I'm struggling a bit with this currently. For some unknown reason, when I request a bundled file, i'm just seeing an empty file contents in the browser.

So for example, when I request: /sb/ReachGCv3MvcModuleNavMenu.js.v1 - I see this:

image

If I check my log output, it shows a FileResult is being produced, and the "Bundle" action on the controller is being run: (However, my breakpoint is not hit on that method which is confusing me!):

image

I should also state that I am deriving from the SmidgeController with my own controller:

    public class BundlerController : Smidge.Controllers.SmidgeController
    {
        public BundlerController(IApplicationEnvironment env, ISmidgeConfig config, FileSystemHelper fileSystemHelper, IHasher hasher, BundleManager bundleManager, IUrlManager urlManager) : base(env, config, fileSystemHelper, hasher, bundleManager, urlManager)
        {
        }      
    }

.. and configuring my own routing during app startup (rather than calling UseSmidge():

           //Create custom route
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    "BundlerComposite",
                    "sc/{file}",
                    new { controller = "Bundler", action = "Composite" });

                routes.MapRoute(
                    "BundlerBundle",
                    "sb/{bundle}",
                    new { controller = "Bundler", action = "Bundle" });

            });

Any ideas on what could be happening? I have incremented the cache version, and verified that the bundle file under app_data definitely has contents.

[Question] - Cache Busting

ASP.NET 5 has a handy way of cache busting via the asp-append-version tag:

<link rel="stylesheet" href="~/Css/somecssfile.min.css" asp-append-version="true"/>

This appends some file version hash to the url - which will mean the url changes when the file changes:

<link rel="stylesheet" href="/css/somecssfile.min.css?v=UdxKHVNJA5vb1EsG9O9uURFDfEE3j1E3DgwL6NiDGMc" />

How does cache busting work with Smidge? Can we just continue to use the asp-append-version tag helper?

Won't work with .NET Core RC1

Hi,

First of all, thank you for this amazing tool, its unfortunate that the old optimization method was left out of ASP.NET 5.

I have tried everything and can't get this package to work with .NET Core RC1 and MVC 6.

I in fact recreated your sample app and it still doesn't work with my dnx, any ideas?

Rtm?

Now that RTM has been released, probably worth updating!

Fluent syntax for declaring bundles

Example

app.UseSmidge(bundles =>
{                
    bundles.Create("test-bundle-2", WebFileType.Js, "~/Js/Bundle2")
        .WithEnvironmentOptions(BundleEnvironmentOptions.Create()
                .ForDebug(builder => builder
                    .EnableCompositeProcessing()
                    .EnableFileWatcher()
                    .SetCacheBusterType<AppDomainLifetimeCacheBuster>()
                    .CacheControlOptions(enableEtag: false, cacheControlMaxAge: 0))
                .Build()
        );                
});

Feature Request: Add option for in-memory bundle cache

Would it be straight forward to create a configuration option that uses in-memory caching of the bundles instead of disk?

I would prefer to incur the overhead re-generating the bundles when the application restarts as opposed to having to delete the cache folder or increment the version every deployment. For applications hosted in an Azure always on scenario a restart generally only occurs when a new deployment is performed anyway.

Support adding config directly to appSettings.json

I am just in the process of setting Smidge up (thanks for making this!)
I noticed this bit:

Add a config file to your app root (not wwwroot) called smidge.json with this content:

Would it be possible for configuration to be added to the appSettings.json file instead? If Smidge uses IConfiguration this should just work?

FileSystemHelper and Files outside wwwroot directory

I'm building a modular application, where projects can contain their own "wwwroot" directory.
I register an IFileProvider - a "CompositeFileProvider" which aggregates each projects "wwwroot" directory, enabling MVC framework to "see" the files from those locations.

When using Smidge, smidge assumes all paths map to a location within env.wwwroot which in my case is not true.

It would be better if Smidge could leverage an IFileProvider, such that it didn't make any assumptions about where those files are physically located.

[Idea] - File watching, and re-bundling

Have an idea.

IFileProvider's allow you to "watch" given files for changes by registering a delegate / callback.

Perhaps we could enhance smidge to also watch the source / input files using that mechanism, and then when a change is detected, re-execute the pipeline?

I'll experiment in a branch

CssMinifier not thread safe

This was due to these pre-processors being singletons and not transient. Now they are request scoped and the thread safety issue is fixed

Source map declarations, and comments

When smidge processes a file, the file may contain a source map declaration:

//# sourceMappingURL=jquery.min.map

These are useful for debugging purposes, when you typically wouldn't have smidge enabled.

However when smidge is enabled, its going to leave that sourcemap declaration in the output bundle, and the browser will attempt to load the sourcemap relative to the bundle file location - and as we don't attempt to move sourcemap files to the bundle file location then the browser wont finr the sourcemap and you see an error in the console.

The original sourcemap is kind of useless anyway after smidge has processed the file because as smidge can perform pre-procesisng, the new source code will no longer match the original sourcemap - so the sourcemap is kind of redundant when smidge is on.

For this reason I think a couple of new pre-processors might be a good idea:

  1. RemoveSourceMapsPreProcessor - this will do what it's name suggests by removing sourcemap declarations from the script contents.
  2. RemoveCommentsPreProcessor - I think this preprocessor is a nicety to avoid issues like #23 and as sourcemap declarations are a form of comment block, this would potentially take care of the sourcempas issue as well.

Feature Request: Add Options to Control Etag and Cache-Control headers.

The following options would be beneficial to those of us more concerned with the "Bundling Workflow" vs all the optimizations. I imagine it would be trivial to add to the SmidgeOptions...

EnableEtag = false
CacheControlMaxAge = integer (0 == disabled).

The idea is I can work on all my build processes to auto-version and whatnot once I've got an MVP, instead of needing to solve for cache-busting/versioning while my app is still being developed. I know "debug==true" is an option, but we currently stage against the bundled/minified resources and having to worry about forgetting to increment versions / clear cache and all of that during this process is overhead I'd like to push off post MVP.

JsMin errors minifying jquery

When attempting to use the JsMin preprocessor against jquery (latest version) it gives this error:

An unhandled exception occurred while processing the request.

Exception: Error: JSMIN Unterminated set in Regular Expression literal: 47
Smidge.FileProcessors.JsMin.action(Int32 d) in JsMin.cs, line 257

JsMin - Singleton not thread safe

Running the website from master, hit a problem on site startup that happens sporadically:

image

Following through the code this happens when two threads / tasks access JsMin at the same time. This happens for me randomly on startup of the website and not sure why - it doesn't always seem to happen.

JsMin isn't thread safe, so both threads enter JSMin and create an instance of a writer and store it in the same private field:

image

One thread then disposes of that instance, and the second thread hits the exception trying to write to the now disposed instance.

JsMin is registered as a singleton instance:

 services.AddSingleton<IPreProcessor, JsMin>();

The simplest fix for this would be to register it as scoped I guess.

I'll make that change unless you spot an issue with that.

This may explain some of the other odd issues I was seeing, if the same reader and writer was being used by different threads / minification tasks then it may have garbled the input / output leading to weird exceptions.

Logging

Would be nice if Smidge would resolve an ILogger and write some logging for useful events, like:

  1. When a new bundle file is created
  2. When an individual file is written to a bundle
  3. When an individual file is being pre-processed
  4. When a bundle is being resolved from cache.

Add support for recursive directory search / patterns

It doesn't look like Smidge is supporting recursive directory search when building a bundle.

Folder Structure

-wwwroot
--lib
---jquery
----jquery.js

Setup

services.AddSmidge(config).Configure<Bundles>(bundles => {
        bundles.Create("jquery", WebFileType.Js, "~/lib*js");
});

jquery.js does not get found, regardless of debug mode when rendering. If I move jquery.js into the lib folder directly, it works.

Load balancing support for non pre-defined bundles

Currently LB will really only work for pre-defined bundles. It could work for inline and non-named bundles too but i haven't got around to that just yet. There's really 2 ways to make this work:

  • Swap the IUrlManager for a base64 Url Manager. This is currently what ClientDependency (https://github.com/Shazwazza/clientdependency) does (see: https://github.com/Shazwazza/ClientDependency/wiki/Composite-Files#url-types). This means that the URLs themselves contain the assets that need bundling/processing so it doesn't matter which server the request gets sent to. This works but the URLs get quite ugly/long and need to be split and they need to include an anti-forgery value.
  • Create a Url/File mapping provider that can be swapped out with a centralized cache (i.e. a database, redis cache, etc...)

Both options would mean that the pre-processing happens during the bundle request instead of during the html rendering request, so the logic for this would need to be abstracted out since currently that all just happens in the PreProcessManager.ProcessAndCacheFileAsync during the SmidgeHelper.GenerateUrlsAsync

Core RC2 Support?

Any plans of upgrading the current package and its dependencies to support RC2?

Can't get your updated sample app to work for me.

Css minification problem [RC4]

Hi,

Trying out RC4 today,

When trying to bundle Font Awesome 4.5.0:

            bundleBuilder.WithBundle(CssBundleNames.VendorDefaultCss.ToString(), BundleFileType.Css, "~/lib/font-awesome/css/font-awesome.css");

        @await BundleHelper.CssHereAsync(CssBundleNames.VendorDefaultCss.ToString())

I get:

image

netstandard

As Smidge is a library, it should probably target netstandard (Atleast that's my understanding, Applications target netcoreapp).

I'll add netstandard and submit a PR for review.

Using different script types

Hi,

Does Smidge allow for setting script types when using code defined script tags in razor?

For example using client side render react for example

  bundles.Create("react-bundle-1", //bundle name
            new JavaScriptFile("~/Js/Bundle1/a1.jsx").ScriptType("text/babel"),
            new JavaScriptFile("~/Js/Bundle1/a2.jsx"));

then in razor

@await Smidge.JsHereAsync("test-bundle-1")

this would generate

<environment names="Development">
    <script src="react-bundle-1" type="text/babel" debug="true"></script>
</environment>
<environment names="Staging,Production">
       <script src="react-bundle-1" type="text/babel"></script>
</environment>

Implement abstract cache buster: ICacheBuster

The cache buster used should be pluggable - by default it will use the config based cache buster but this could be replaced by a developer with anything. We can specify a default for the debug or production environment options, but also specify a cache buster for an individual bundle.

How to use with RequireJs (AMD)

With RequireJS you have to construct a javascript object to configure it.

You need to accomplish two things.

  1. Add a "path" to the bundle file, and give this a name.
  2. Specify which "modules" are in that bundle file, using a "bundles" section.

Here is an example:

 @<script type="text/javascript">
        require.config({
            paths: {
                "primary": "/js/modules/bundlefile"
            },
          bundles: {
             'primary': ['MainMenuViewModel', 'SomeOtherModule', 'YetAnotherModule']
            }
        });
 </script>

You can then do this in javascript:

 require(['MainMenuViewModel'], function (vm) {
           vm.SomeThing();
}

So based on that configuration, RequireJs uses the bundles config, to map the module name "MainMenuViewModel" to the javascript file: "primary", and it uses the paths section to determine that the "primary" script is loaded from /js/modules/bundlefile.js

I'm now trying to get this working with Smidge bundles.

Smidge, doesn't seem to produce a deterministic file name for the bundle file. This means you can't currently manually maintain this mapping, i.e what to put for question marks below?

 @<script type="text/javascript">
        require.config({
            paths: {
                "primary": "/App_Data/Bundler/Cache/ ?? ?? "
            },
            bundles: {
             'primary': ['MainMenuViewModel', 'SomeOtherModule', 'YetAnotherModule']
            }
        });
 </script>

Is there some way of getting the file name for the bundle file so that I can generate this config in a razor view.

Combining issue, with comment blocks

I am combining jquery.min.js with knockout-es5.js in a bundle.

However something funny happens.

The last line of jquery.min is this:

//# sourceMappingURL=jquery.min.map

The top of knockout-es5.js is this:

/*!
 * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
 * Copyright (c) Steve Sanderson
 * MIT license
 */

However when Smidge produces the bundle file, it looks like this:

//# sourceMappingURL=jquery.min.map/*!
 * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
 * Copyright (c) Steve Sanderson
 * MIT license
 */

The browser complains:

image

This is probably because just appends to the previous script, but in this case i'm guessing a comment block is only valid at the start of a line?

I am using the latest code base to replicate this.

Named bundles should execute the pipeline (if not already done) when the bundle URL is visited

The following setup is not working when debug is false.

"Smidge": "1.0.0"

bundles.Create("jquery", WebFileType.Js, "~/lib/jquery/3.1.0/jquery.js");
@await Smidge.JsHereAsync("jquery", false)

The Javacript file is non-minified, unmodified distribution of jquery 3.1.0 hosted localy in wwwroot/lib/...

In debug mode, the file is found and included as scrip tag. When debug is false, it looks like Smidge is creating assets correctly in the disk cache, but the content rendered when the bundle is requested by the browser is just a semi-colon ';'.

Using a dot in a bundle name causes an issue.

It seems that there are some rules around bundle names that probably should be documented. It appears its not valid to use a "." in a bundle name, as this then causes an exception in BundleModel:

  public BundleModel(IUrlManager urlManager, IActionContextAccessor accessor)
            : base("bundle", urlManager, accessor)
        {
            if (!ParsedPath.Names.Any())
            {
                throw new InvalidOperationException("The bundle route value does not contain a bundle name");
            }

            _bundleName = ParsedPath.Names.Single();

        }

Which errors on ParsedPath.Names.Single().

Integration with Castle Windsor

Hey,

I'm trying to implement Smidge in my application. When page load, I have this errors on file:

Castle.MicroKernel.ComponentNotFoundException: No component for supporting the service Smidge.Controllers.SmidgeController was found
   at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
   at Castle.Windsor.MsDependencyInjection.ScopedWindsorServiceProvider.GetServiceInternal(Type serviceType, Boolean isOptional)
   at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAllActionFiltersAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeExceptionFilterAsync>d__25.MoveNext()

Any idea? Thank you!

JavascriptServices

Just stumbled accross the JavascriptServices package - have you seen that yet? I think it looks quite interesting in that it would allow us to create pre-processors that leverage npm tooling. There are minifiers / transpilers available on npm platform that support things like sourcemaps as well as typescript files - so might open up some possibilities.

Add a Typescript processor?

Does this sound like a good idea? If so perhaps I'll work on a PR?

For example in my project I have several typescript files, and a tsconfig.json file.

image

At the moment, I rely on a gulp task and various gulp plugins, which:

  1. Initialise a typescript project form a typescript config file (tsconfig)
  2. Compile the ts source files to js (honouring the tsconfig file settings), and produce source maps
  3. Concatenate and Uglify, outputting a single file to a known location.

Here is an example:


 var gulp = require("gulp"),  
    ts = require('gulp-typescript'),    
    sourcemaps = require('gulp-sourcemaps'),   
    concat = require("gulp-concat")

// creates a tsproject from the tsconfig file.
var tsProject = ts.createProject('./Scripts/tsconfig.json', { typescript: require('typescript'), sortOutput: true });

gulp.task('compile:typescript', function () {
    var tsResult = tsProject.src()
    .pipe(sourcemaps.init()) // intialises sourcemaps
    .pipe(ts(tsProject));

    tsResult.js    
   .pipe(sourcemaps.write('./', {
       sourceMappingURLPrefix: '/js/generated',
       includeContent: false,
       sourceRoot: '/Scripts'
   }))
   .pipe(gulp.dest('./'))  
    return tsResult.js    
       .pipe(concat('./wwwroot/js/generated/ts.min.js'))
       .pipe(uglify())     
       .pipe(gulp.dest("."));

});

Do you think it's a good idea to extend Smidge with such capabilities for typescript? If so, how would this be achieved with Smidge, what extensibility points would need to be implemented?

Control the minified address?

Is there a way to control the url? so instead of Smidge creating /sb/js.js.v1 for my js files, can I tell it to give me a different url e.g /js ?

This was possible with previous MVC 5 I think, let know if Smidge has this.

Default pre-processor pipeline - don't enable JsMin for .min.js files convention

Just wondered if it would be a good enhancement for Smidge to not use the JsMin PreProcessor by default for .js files ending in .min.js. ? Not sure how that could work right now but I am guessing it owuld be something like after the PreProcessorPipelineFactory is invoked to get the default pipeline for .js files, inspect that pipeline, and if there are files in the bundle ending in .min.js and those files don't have a custom pipeline set, then give those files a custom pipeline based on the default, minus JsMin ?

Guidance around bundling external assets

This is not a Smidge issue exactly, but is loosely related. I was wondering what best practice might be for dealing with external resources such as jquery, font-awesome etc. Would it be best to bundle these all together into a single local file?

MVC 6 allows you to include references to external files (from a CDN etc) with a fallback to a local file when that file isn't available like this:


<environment names="Test,Staging,Production">
        @*<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />*@
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"
              asp-fallback-href="~/lib/font-awesome/css/font-awesome.min.css"
              asp-fallback-test-class="fa" asp-fallback-test-property="display" asp-fallback-test-value="inline-block"/>        
    </environment>

So at the moment i'm assuming its best to stick to this mechanism and do not bundle external resources, just let them load individually..

Calling a wrong style/script address

I have below code in startup.cs
bundles.Create("style", new CssFile("/theme/design.css")); (works fine)

Now when I call style from the root page (e.g: /) it works and calls this css file: /sb/style.css.v1

But when I call any other page such as /home/about, Smidge gets the css address wrong and calls: /home/sb/style.css.v1

/auth/login will result in Smidge looking for /auth/sb/style.css.v1 instead of just /sb/style.css.v1

Same with JS

CssRewriteUrlTransform

I have just became aware of this class from the System.Web.Optimization library: https://msdn.microsoft.com/en-us/library/system.web.optimization.cssrewriteurltransform(v=vs.110).aspx

Basically, when bundling using system.web.optimization you can allow it to re-write any relative url's in the CSS file so that still works after its moved to the bundle file location. This is useful for CSS files that reference local assets like FA does with its fonts files..

Might be an idea to try and implement this kind of thing for Smidge as a feature - assuming it doesn't do that already?

Named bundles exception when no resources found via pattern matching/search.

If you create a named bundle, and the bundle that acquires it's resources via pattern matching / search (e.g. all css files in a directory) the bundle will throw the following exception if at least 1 matching file doesn't exist in the search directory.

Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.FileResult'

What should happen is that RenderJssHereAsync and RenderCssHereAsync should simply not render tags for named bundles that don't contain any assets... If someone requests a bundle that is empty, smidge should just return 404 not found or an empty 200 response - up to you, not sure what is appropriate.

Note, this only occurs when debug == false and the pipeline is executed.

I think you could try to reproduce with...

bundles.Create("styles", new CssFile[0]));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.