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
organizing custom javascripts in asp.net mvc 4
提问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 scripts
folder is the way to go.
you can create a new bundle in the appstart\BundleConfig.cs
file 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 bundle
to your view like this:
然后bundle
像这样添加到您的视图中:
@section scripts{
@Scripts.Render("~/bundles/custom")
}
this will be rendered at the @RenderSection("scripts", required: false)
line on your layout
file.
这将呈现在@RenderSection("scripts", required: false)
您layout
文件的行上。
OR
To call only one specific script
for your view
you can do:
或
只呼叫一个特定script
于您的人,view
您可以:
@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.
注意:您可以将脚本文件从solution explorer
拖入该部分。您不必编写整个路径。
编辑- 似乎很重要,所以我从上次评论中复制了这一点:
为了使用,minification
您需要将脚本添加到包表中,然后添加BundleTable.EnableOptimizations = true;
到BundleConfig
文件中或<compilation debug="false"
在web.config
文件中设置。
回答by Darin Dimitrov
You could organize your scripts in the Scripts
folder:
您可以在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.
当然,您可以捆绑总是在一起的脚本。