vtfuture / RequireJSDotNet

RequireJS for ASP.NET MVC
http://requirejsnet.veritech.io
MIT License
94 stars 46 forks source link

Allow fallback paths #67

Closed washamdev closed 7 years ago

washamdev commented 8 years ago

The RequireJS documentation describes how you can define two entries in an array to a path, with the second path serving as a fallback in case the first file fails to load. Like so:

"paths": {
    "bootstrap": [ "//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min", "bootstrap.min" ]
}

I tried using this same method in the RequireJS.json config file but encountered this error:

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'.

I noticed that in the \RequireJsNet\RequireJsNet\Configuration\JsonReader.cs file starting on line 100, if the Value of the property isn't a string, it assumes the property is a JObject. I wonder if something like this could be done?

if (prop.Value.Type == JTokenType.String)
{
    result.Value = prop.Value.ToString();
}
else if (prop.Value.Type == JTokenType.Array)
{
    var pathArr = (JArray)prop.Value;
    result.Value = string.Join("|", pathArr.Select(x => x));
}
else
{
    var pathObj = (JObject)prop.Value;
    result.Value = pathObj["path"].ToString();
    result.DefaultBundle = pathObj["defaultBundle"].ToString();
}

The problem then is that result.Value expects a single path in a string, not a delimited string, so it would have to know how to handle that. Could it accept a delimited string representing multiple paths and pass that to RequireJS?

aquamoth commented 7 years ago

To support this for all scenarios is a bit more tricky than your suggestion. I'm working on a fix that only needs a bit more unit testing to be stable.

aquamoth commented 7 years ago

The referenced commit solves this issue without known side-effects.

The compressor bundles the first local path for all dependencies and ignores dependencies that are only resolved by url.

The fallback functionality is displayed in RequireJSNet.Examples on /Home/Index. Note there is first a load failure for jquery but it is automatically resolved by requirejs fallback feature.

The bundling of files with multiple paths is displayed in RequireJSNet.Examples on /Home/Complex. Note there is no load failure for jquery here because it uses the bundled version.