CSS/JS bundle in single file in mvc when publish with release option

泄露秘密 提交于 2019-11-30 08:46:00

I have experienced this before when using bundling.

Say for instance your css file is located at: /Content/css/css.css

This css file then makes a reference to another file, or for example an image at /Content/images/image1.png via url('../images/image1.png').

You then set up your css bundle @ /bundles/css.

All appears great in debug mode. However, when you set <compilation debug="false" .... in your web.config, suddenly the references made in the css file breaks. If you open your console in Firebug/Chrome dev tools and check the network tabs, you'll see resources failing to load, from an incorrect URL.

This happens because when debug mode is off, all the files are bundled and minified like they would be in production. In this case, the CSS file would be bundled and served from the URL /bundles/css. This results in the relative URL reference breaking. Where it once referenced /Content/images/image1.png, it now references /images/image1.png.

You have a few options to solve this:

  1. Serve your bundled css files from the same folder as the actual css files. eg. /Content/css/cssbundle. This can become very tedious quickly.
  2. Change all relative references in your css files to absolute references. eg. ../images/image1.png would become /Content/images/image1.png. This does mean you can't use a lot third party CSS bundled out of the box, you would have to check/change relative references if you wanted to bundle them.
  3. Use the BundleTransformer nuget package. It automatically transforms relative urls to absolute ones during the bundling process.

    The main differences of StyleTransformer and ScriptTransformer classes from a standard implementations: ability to exclude unnecessary assets when adding assets from a directory, does not produce the re-minification of pre-minified assets, support automatic transformation of relative paths to absolute in CSS-code (by using UrlRewritingCssPostProcessor), etc.

I personally recommend 3 as it is the easiest to maintain long term.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!