【问题标题】:Relative paths and Bundle configuration相对路径和 Bundle 配置
【发布时间】:2014-04-27 16:51:30
【问题描述】:

我的 BundleConfig.cs 文件中有以下内容:

bundles.Add(new StyleBundle("~/Content/css").Include(
            "~/Content/mainstyle.css",
            "~/Content/layout/style.css", /* <<< HERE, the folder is different */
            "~/Content/bootstrap.css",
            "~/Content/site.css"));

~/Content/layout/style.css 文件中:

#page {
    width: 1000px;
    margin: 0 auto;
    background: url(images/img04.jpg) repeat-y left top;
}

如果我们知道捆绑包会将所有 css 合并为一个 (?!) 服务器将如何看到 img04.img (url(images/img04.jpg)) 的链接,如 Content/images/ , Content/css/images/Content/layout/images?

【问题讨论】:

    标签: css .net asp.net-mvc bundling-and-minification


    【解决方案1】:

    在对主题进行一些谷歌搜索之后,CssRewriteUrlTransform 类似乎确保图像 url 从动态捆绑 css 文件中工作,如下所示:

    bundles.Add(new StyleBundle("~/Content/css").Include(
                "~/Content/mainstyle.css",
                "~/Content/bootstrap.css",
                "~/Content/site.css")
               .Include("~/Content/layout/style.css", new CssRewriteUrlTransform()));
    

    如果这没有帮助,但您希望使用捆绑,请将您的捆绑分成每个文件夹的部分。把文件夹路径放到bundle“name”里面,像这样new StyleBundle("~[folder_path]/[any word, like 'css' ot whatever you like]")

    bundles.Add(new StyleBundle("~/Content/css").Include(
                "~/Content/mainstyle.css",
                "~/Content/bootstrap.css",
                "~/Content/site.css"));
    
    bundles.Add(new StyleBundle("~/Content/layout/css").Include(
                "~/Content/layout/style.css"));
    

    【讨论】:

    • .net 应用程序的良好解决方案,我将您的解决方案添加到我的答案中以供将来参考和访问者使用。
    • 我还添加了另一个解决方案,因为最后第一个在我的情况下不起作用......
    【解决方案2】:

    这是合并文件时的常见问题,您需要:

    1. 为这些 url 设置服务器端重写规则。

    2. 将您的 CSS 图像转换为 base64 并使 CSS 文件独立 任何外部图像。

    3. Content 目录加载组合 CSS,所以 images/ 将是 相对于该目录。

    4. 更新 CSS 文件中的路径。

    5. 在“预期”目录中拥有图像的副本。 (较少的 可维护)

    对于.net 应用程序,如serhio 所述,CssRewriteUrlTransform 类将动态更新捆绑文件中指定包含的url 引用。 serhio提供的例子:

    bundles.Add(new StyleBundle("~/Content/css").Include(
                "~/Content/mainstyle.css",
                "~/Content/bootstrap.css",
                "~/Content/site.css")
               .Include("~/Content/layout/style.css", new CssRewriteUrlTransform()));
    

    【讨论】:

    • 我还是不明白,具体情况下服务器会走什么路径?
    • @serhio 对于图像/它将是(组合文件的位置)/图像/
    • 那么,合并文件的位置在哪里?
    • @serhio 在您的情况下,根据您的代码,它是 ~/Content/
    猜你喜欢
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2023-03-04
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2013-07-14
    相关资源
    最近更新 更多