MVC 3中CSS, Javascript及其命名约定的管理

Management of CSS, Javascript and their naming conventions in MVC 3

本文关键字:命名约定 管理 Javascript CSS MVC      更新时间:2023-09-26

最近我正在构建一个严重依赖javascript/jquery的项目。当部分视图被呈现时,它们需要应用一些javascript或CSS样式。你有什么有效的方法来管理这些文件吗?

我发现需要在我自己的项目中这样做,因为我希望能够为每个视图拥有单独的javascript'css文件。

我最终做的是创建一个控制器来为我聚合服务器上的文件,然后只发送一个css'js文件到浏览器。答案可能比你想要的更复杂,所以我推荐第一部分。

你可以创建一个扩展方法,你可以在每个页面的顶部调用它来为请求添加一个JS文件到TempData字典中的列表中。然后从Layout中调用一个单独的方法,该方法将呈现任何额外的链接。

这是有效的,因为TempData仅为请求保留,并且布局的视图是最后呈现的(在所有视图和局部运行之后)。

我有一个类的完整的例子在这里:http://pastebin.com/EUC2fAca但我也形成链接到我的聚合器,所以你需要修改。要点如下:

public static string JSKey = "pageJSList";      
private static void AddToDictionary(HtmlHelper helper, string[] files, string key)
{
    if (files == null || files.Length == 0)
        return;
    TempDataDictionary dict = helper.ViewContext.TempData;
    if (!dict.ContainsKey(key))
        dict.Add(key, new List<string>());
    (dict[key] as List<string>).AddRange(files);
}
private static void InsertToDictionary(HtmlHelper helper, string[] files, string key)
{
    if (files == null || files.Length == 0)
        return;
    TempDataDictionary dict = helper.ViewContext.TempData;
    if (!dict.ContainsKey(key))
        dict.Add(key, new List<string>());
    (dict[key] as List<string>).InsertRange(0, files);
}       
public static void AddJS(this HtmlHelper helper, params string[] files)
{
    AddToDictionary(helper, files, JSKey);
}
public static void AddJSToTop(this HtmlHelper helper, params string[] files)
{
    InsertToDictionary(helper, files, JSKey);
}
public static MvcHtmlString GetJsTagHtml(HtmlHelper helper)
{
    var files = helper.ViewContext.TempData[JSKey] as List<string>;
    StringBuilder tags = new StringBuilder();
    string jsTemplate = "<script type='"text/javascript'" src='"/Scripts/{0}'"></script>";
    foreach (string file in files)
    {
        tags.AppendLine(String.Format(jsTemplate, file));
    }
    return MvcHtmlString.Create(tags.ToString());   
}

你会想要Insert方法在布局上运行,因为,再次,它是最后运行的,所以你会想要插入jquery库或其他依赖项,应该在列表的第一个。

你的GetJS方法应该返回一个MvcHtmlString,它包含了你需要的所有标签。

希望有帮助,不要太啰嗦=)

CSS文件和JavaScript文件以及几乎任何其他文件的管理取决于您的分类收藏,或者换句话说,您的分类法。我认为更好的问题是,我应该遵循什么准则,才能使我的项目更成功。例如,无论您如何管理和分类JavaScript文件,都尽量不要在一个页面中包含许多文件,因为每个文件都向服务器发出单独的HTTP请求。或者,尽量在命名上保持一致,这样以后就不会对代码感到困惑了。对于CSS和JavaScript,我建议使用LDSW。

使用webpack管理您的文件。一个简单的webpack设置看起来像

# /webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const postcssPresetEnv = require("postcss-preset-env");
module.exports = (env, argv) => {
  const devMode = argv.mode !== "production";
  return {
    mode: argv.mode,
    entry: {
      // Main / Shared
      'main': './Content/styles/main.scss',
      'theme': './Content/styles/theme.scss',
    
      // Pages
      'page-home': './Content/styles/pages/home/home.scss',
      'page-register': './Content/styles/pages/register/register.scss',
      // If we import _register-forms.scss at the top of register.scss,
      // there is no need to include it here. That has nothing to do with webpack.
      // Components / Partials
      'component-search': './Content/styles/components/search/search.scss',
      // Javscripts
      'client': './Content/client/client.js',
      'home': './Content/client/pages/home/index.js',
      'component-search': './Content/client/components/search/search.js',
      // Got more partial files? Just import { Helper } from './_search-helpers.js' inside  
      // search.js, and the code will be included.
    },
    resolve: {
      alias: {
        // Setup optional aliases
        pages: path.resolve(__dirname, 'Content/styles/pages'),
        components: path.resolve(__dirname, 'Content/styles/components'),
      }
    },
    output: {
      path: path.resolve(__dirname, "Content/dist"),
      publicPath: "/css",
      filename: devMode ? "js/[name].js" : "js/[name].min.js"
    },
    ... more webpack stuff here.

然后,你不需要在webpack中引用所有的scss文件。例如,现在您可以这样导入较小的文件:

# /Content/styles/pages/register/register.scss
@import './_register-form'; 
@import './_register-layout'; 

你不需要在你的webpack.config.js中包含它们,因为它们会被拉入寄存器。SCSS与SCSS @import.

同样,在你的javascript文件中,你可以只导入你需要的。

# /Content/client/components/search/search.js
import { SearchHelpers }  from '_search-helpers'; 

search.js现在将包含_search-helpers.js中的所有内容。

对我来说,这似乎是MVC项目中前端代码的逻辑结构。