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

发布于 2024-11-19 09:05:05 字数 106 浏览 3 评论 0原文

最近我正在构建一个严重依赖 javascript/jquery 的项目。当渲染某些部分视图时,它们需要应用一些 JavaScript 或 CSS 样式。您对管理这些文件的高效/有效方法有什么想法吗?

Recently I am building a project heavily relies on javascript/jquery. When some of the partial views are rendered, they need to apply some javascripts or CSS styles. Do you have any ideas on an efficient/effective way to manage those files?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

趁年轻赶紧闹 2024-11-26 09:05:05

我发现需要在自己的项目中执行此操作,因为我希望能够为每个视图都有一个单独的 javascript\css 文件。

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

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

这是有效的,因为 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。

希望对您有所帮助,并且不会太啰嗦 =)

I found a need to do this in my own project, because I wanted to be able to have a separate javascript\css file for each view.

What I ended up doing was creating a controller to aggregate the files on the server for me and then send only one css\js file to the browser. The answer is perhaps more intricate than you requested though, so I'll recommend the first part.

You can make an extension method that you can call at the top of each page to add a JS file to a list in the TempData dictionary for the request. You then call a separate method from the Layout that will render any additional links.

This works because the TempData is kept just for the request, and the layout's View is rendered last (after all the views and partials run).

I have a full example of a class here: http://pastebin.com/EUC2fAca but i'm also forming links to my aggregator, so you'll need to modify. The gist is as follows:

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());   
}

You'll want the Insert method to run it on the layout because, again, it runs last so you'll want to Insert jquery libraries or other dependencies that should be first on the list.

Your GetJS method should probably return an MvcHtmlString that contains all of the tags you need.

Hope that helps and wasn't too long winded =)

不知所踪 2024-11-26 09:05:05

CSS 文件和 JavaScript 文件以及几乎任何其他文件的管理取决于您的分类收藏夹,或者换句话说,您的分类。我认为更好的问题是,我应该遵循什么指导方针,以使我的项目变得更加成功。例如,无论您如何管理和分类 JavaScript 文件,都尽量不要在一个页面中包含很多 JavaScript 文件,因为每个文件都会向服务器发出单独的 HTTP 请求。或者,尝试命名尽可能一致,这样,将来您就不会被代码迷惑了。对于 CSS 和 JavaScript,我建议 LDSW

Management of CSS files and JavaScript files and almost any other file depends on your categorization favorites, or in other terms, your taxonomy. I think the better question is, what guidelines should I follow, to make my project become more successful. For example, however you manage and categorize your JavaScript files, try to not have many of'em in a page, as each of'em make a separate HTTP request to the server. Or, try to be as consistent in naming as possible, so that, in future you won't get puzzled by your code. For CSS and JavaScript, I suggest LDSW.

贩梦商人 2024-11-26 09:05:05

使用 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 @import 拉入 register.scss 中。

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

# /Content/client/components/search/search.js

import { SearchHelpers }  from '_search-helpers'; 

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

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

Use webpack to manage your files. A simple webpack setup could look like

# /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.

Then, you don't need to reference all of your scss files in webpack. For example, now you can just import smaller files with this:

# /Content/styles/pages/register/register.scss

@import './_register-form'; 
@import './_register-layout'; 

You don't have to include them in your webpack.config.js, because they are pulled into register.scss with the scss @import.

And likewise, in your javascript files you can just import what you need.

# /Content/client/components/search/search.js

import { SearchHelpers }  from '_search-helpers'; 

search.js will now contain everything from _search-helpers.js.

To me, this seems like a logical structure for front-end code in an MVC project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文