问题
Today I started to add some client side Javascript code, like a nice date picker or some collapsing modals to my ASP.NET Core MVC WebApp.
I don't need all this settings on initial stuff in each view, so on my opinion the cleanest way is to define for each view a own js file.
First would I like to know, if this is the right way to do stuff like this? Or just take a big .js file, give each element a unique id and work over that?
So I was looking for achieving this in a nice way. But I only found partial solutions and build out of this my own.
In my wwwroot/js folder I'm reflecting the structure of the Views folder.
Like: Views/Home/Index => wwwroot/js/home/index.js
To minimize the .js I just append a entry to the bundleconfig.json like:
{
" outputFileName": "wwwroot/js/home/index.min.js",
"inputFiles": [
"wwwroot/js/home/index.js"
],
// Optionally specify minification options
"minify": {
"enabled": true,
"renameLocals": true
},
// Optionally generate .map file
"sourceMap": false
}
and get a wwwroot/js/home/index.min.js.
To load the right .js file I use the following code in my _Layout.cshtml:
@if (File.Exists($"wwwroot/js/{ViewContext.RouteData.Values["controller"]}/{ViewContext.RouteData.Values["action"]}.min.js"))
{
<script type="text/javascript" src="~/js/@ViewContext.RouteData.Values["controller"].ToString().ToLower()/@ViewContext.RouteData.Values["action"].ToString().ToLower()@{}.js"></script>
}
To determine the right environment I use the predefined Development and Staging,Production tags.
To the big second question: Would you do this the same way, or do you have a better approach for solving this?
来源:https://stackoverflow.com/questions/44244115/asp-net-core-mvc-view-and-environment-specific-javascript-file