javascript 在 asp.net mvc 4 中组织自定义 javascripts

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14621988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:08:30  来源:igfitidea点击:

organizing custom javascripts in asp.net mvc 4

javascriptasp.net-mvc-4bundle

提问by Sam

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.

我是 mvc 4 的新手,我想知道我应该把我的自定义 javascript 文件放在哪里。“自定义”是指仅在特定视图或局部视图中使用的脚本。

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.

我也使用区域,因此增加了复杂性。我正在考虑将我的脚本放在应用程序根目录的 Script 文件夹中,然后放在自定义子文件夹中。

How would I then reference the scripts in my Views ? Should I use custom Bundles ?

我将如何在我的视图中引用脚本?我应该使用自定义捆绑包吗?

回答by Yoav

i think that adding your scripts to a custom folder in your scriptsfolder is the way to go. you can create a new bundle in the appstart\BundleConfig.csfile as follows:

我认为将脚本添加到文件夹中的自定义文件scripts夹是可行的方法。您可以在appstart\BundleConfig.cs文件中创建一个新包,如下所示:

bundles.Add(new ScriptBundle("~/bundles/custom").Include(
                   "~/Scripts/Custom/myCustom.js",
                   "~/Scripts/Custom/myCustom2.js"));

and than add the bundleto your view like this:

然后bundle像这样添加到您的视图中:

@section scripts{

 @Scripts.Render("~/bundles/custom")

}

this will be rendered at the @RenderSection("scripts", required: false)line on your layoutfile.

这将呈现在@RenderSection("scripts", required: false)layout文件的行上。

OR
To call only one specific scriptfor your viewyou can do:


只呼叫一个特定script于您的人,view您可以:

@section scripts{
<script src="~/Scripts/Custom/myCustom.js"></script>
}

note: you can drag the script file from the solution explorerinto 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 minificationyou need to add your script to the bundle table and either add BundleTable.EnableOptimizations = true;to the BundleConfigfile or set <compilation debug="false"in your web.configfile.

注意:您可以将脚本文件从solution explorer拖入该部分。您不必编写整个路径。
编辑- 似乎很重要,所以我从上次评论中复制了这一点:
为了使用,minification您需要将脚本添加到包表中,然后添加BundleTable.EnableOptimizations = true;BundleConfig文件中或<compilation debug="false"web.config文件中设置。

回答by Darin Dimitrov

You could organize your scripts in the Scriptsfolder:

您可以在Scripts文件夹中组织脚本:

  • ~/Scripts/Home/foobar.js
  • ~/Scripts/Admin/baz.js
  • ...
  • 〜/脚本/主页/foobar.js
  • ~/Scripts/Admin/baz.js
  • ...

Should I use custom Bundles ?

我应该使用自定义捆绑包吗?

Sure, you could bundle the scripts that always go together.

当然,您可以捆绑总是在一起的脚本。