I'm new to mvc 4 and I'm wondering where I should put my custom javascript files. By 'custom', I mean scripts that are only used in specific Views or PartialViews.
I use Areas too, so that adds up the complexity. I was thinking about placing my scripts in the Script folder at the root of the application and then in a Custom sub-folder.
How would I then reference the scripts in my Views ? Should I use custom Bundles ?
i think that adding your scripts to a custom folder in your scripts folder is the way to go.
you can create a new bundle in the appstart\BundleConfig.cs file as follows:
bundles.Add(new ScriptBundle("~/bundles/custom").Include(
"~/Scripts/Custom/myCustom.js",
"~/Scripts/Custom/myCustom2.js"));
and than add the bundle to your view like this:
#section scripts{
#Scripts.Render("~/bundles/custom")
}
this will be rendered at the #RenderSection("scripts", required: false) line on your layout file.
OR
To call only one specific script for your view you can do:
#section scripts{
<script src="~/Scripts/Custom/myCustom.js"></script>
}
note: you can drag the script file from the solution explorer into the section. you don't have to write the entire path.
EDIT - seems important so i copied this from my last comment:
in order to use minification you need to add your script to the bundle table and either add BundleTable.EnableOptimizations = true; to the BundleConfig file or set <compilation debug="false" in your web.config file.
You could organize your scripts in the Scripts folder:
~/Scripts/Home/foobar.js
~/Scripts/Admin/baz.js
...
Should I use custom Bundles ?
Sure, you could bundle the scripts that always go together.
Related
I am new in asp.net mvc and I am trying to include .js files in my project but I could not access it on my browser. Like it.
#Scripts.Render("~/bundles/responds.js")
#Scripts.Render("~/bundles/jquery-1.11.3.min.js")
#Scripts.Render("~/bundles/jssor.slider-22.0.15.mini.js")
<script type="text/javascript">
</script>
Anyone can help me, how can I add these files in mvc project? These files exists in Scripts folder.
You can manually add a .js file to a view with the following example code
#model YourNameSpace.ViewModels.YourViewModel
#Scripts.Render("~/Scripts/yourScript.js")
If you want the files to be bundled & you can add them in App_Start/BundleConfig.cs
Example:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle(("~/bundles/customBundle").Include(
"~/Scripts/yourScript.js",
"~/Scripts/anotherScript.js");
}
You can render your script files for the whole application in the ~/Views/Shared/_Layout.cshtml file or any master page by adding the following code
#Scripts.Render("~/bundles/customBundle")
You can inspect the .js file by browsing to the root of your application & add the path of the .js file or bundle (for this example)
http://localhost:9654/bundles/customBundle
http://localhost:9654/Scripts/yourScript.js
I have solved my problem by just drag and drop script files from Scripts folder to at desired place in Index.cshtml and Visual studio auto generate below code.
<script src="~/Scripts/jquery-1.11.3.min.js"></script>
<script src="~/Scripts/jssor.slider-22.1.5.mini.js"></script>
Which includes the script files in asp.net MVC.
You can use C# code to calculate & generate the right file address as follows:
<script type="text/javascript" src='#Url.Content("~/Content/vendor/jquery/jquery.min.js")'></script>
This pattern can use in *.cshtml files.
I'm looking into migrating a large, homegrown build script for one of our projects to webpack.
One feature it has is it traverses a /views directory and copies the contents of the html files into a main index.html file. This allows us to easily use KnockoutJS's templating feature without putting everything in one file ourselves. Something like this:
for relative_path, full_path in walk(os.path.join(base, "views")):
with open(full_path) as f:
index.append("""<script type="text/html" id="{0}">""".format(relative_path))
index.extend(f)
index.append("</script>")
Ideally, I'd like to be able to do something like require('./views') and have it embed each .html file as <script type="text/html" id="views/foo">...</script>, injecting the text into the script tag and setting the id to the filepath. We have almost 100 different templates, so I'd like to avoid require()ing them individually.
Can I configure html-loader or html-webpack-plugin to do this? I'm wondering if I'll have to write my own webpack plugin or if there's a way I can configure an existing plugin to do what I want.
Thanks!
I think you can accomplish this using require.context and the html loader.
function requireAll(requireContext) {
return requireContext.keys().map(requireContext);
}
// requires and returns html files in the views directory
var modules = requireAll(require.context("./views", true, /^\.html$/));
modules.forEach(function(htmlTemplate){
// code to add each template to document.body
}
I am using VS 2015 + ASP.net vnext + Angular 2 + Typescript + gulp.js. I have automated my scripts/**/*.ts files moving to the wwwroot/app folder. Now I want to do the same for my libraries like Angular 2. I want that a gulp process injects
angular.js inside index.html inside the <environment names="Development"> node;
angular.min.js inside index.html inside the <environment names="Production"> node.
Of course I want that this to happen for all my libs automatically, without having knowledge about a library:
<any>.min.js (production)
<any>.js (development)
The minification of any.js can be done by me.
Actually I would just have to regard all dependencies in package.json... but then I am lost.
Can my idea be done or does there maybe already exist a tool? Or should the workflow broken into more manual steps like I have to copy/paste a certain library?
Or is it possible to take the dependencies name and concat it with .js then search this file under the node_modules folder... (kind of hacky and not safe...)
UPDATE
Rephrase/Refine my question:
How can I automatically add my npm dependencies (not devDependencies) to the environment "Development" node when triggering a certain event like build/clear/etc...
There is a little tag helper for this, called asp-src-include.
Imagine the case where you have a handful of *.js files you want to include:
<script src="/app/app.js"></script>
<script src="/app/controller/controllerA.js"></script>
<script src="/app/controller/controllerB.js"></script>
<script src="/app/service/userservice.js"></script>
etc. You can include all of these with a single `ยด tag.
<script asp-src-include="~/app/**/*.js"></script>
So for Production/Development deployment your Razor markup may look like
<environment names="Development">
<script asp-src-include="~/app/**/*.js"></script>
</environment>
<environment names="Staging,Production">
<script asp-src-include="~/app/**/*.min.js"></script>
</environment>
For this you need the #addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" (starting with RC1 or RC2 it's ' #addTagHelper *, Microsoft.AspNet.Mvc.TagHelpers' - without the double-quotes ) declaration in your *.cshtml files or inside your _Layout.cshtml.
edit
There is an module called gulp-npm-files that does something similar, it copies all *.js files into the target folders. You can see it's source on GitHub in case you want write your own module to extend the functionality.
But that may not be exactly what you want, as the folders often contain multiple files, for example angular2 (AngularJS 2.0) contains dozen of files (*.js and *.ts), but you're mostly only interested in the compiled/minified ones, found in angular2/bundles/* like angular2.js, angular2.min.js or angular.dev.js.
The package.json of the particular dependency provides no information on where to find this compiled files. So I guess, there's no way to automate this unless you want to copy all of the files to wwwroot which makes no sense in my eyes, especially if you want to use asp-src-include, as it makes no difference on what it includes, so you want to minimize the number of *.js files in your wwwroot folder.
I guess the best you can do is to manually copy the dependencies via gulp task and then use asp-src-include to automatically include them into your razor generated html files.
So your problem is that you want to inject the scripts automatically into your HTML, right? You can use the Wiredep module for that.
And for copying the assets to an other folder, there are many modules to copy or link files from one folder to another. Gulp-copy is the first one i could find.
I have a page in my MVC application with only one JavaScript file in it. Should I bundle this file or keep it as is?
My current code
#section scripts{
<script src="~/Scripts/Custom/Home/Index.js" type="text/javascript"></script>
}
I would still suggest you put that file through bundling, advantages you get:
It will get minified for production
Should you add more javascript files later, it will be just a matter of adding those to a bundle, without ever making changes to your HTML template
I want to include javascript files from whole folder and subfolders into a single ASP.NET Bundle. The purpose of this is to load all files from that folder at once.
The idea is to create an angular application and load all app files with a single bundle.
Is this idea ok ?
The problem I have is that the Script tags added to HTML don't respect the subfolder strucutre of my application and the files can't be found.
Bundle config:
bundles.Add(new ScriptBundle("~/bundles/app").IncludeDirectory(
"~/app", "*.js", true));
Folder Structure
app
controller/appMenu.js
modules/navigation.js
app.js
On client side the included tags look like this:
<script src="/app/appMenu.js"></script>
<script src="/app/navigation.js"></script>
I think it might be related to this:
http://aspnetoptimization.codeplex.com/workitem/105
What version of the System.Web.Optimizations assembly are you using?