Monday, 30 July 2012

Config Settings into JavaScript using IBundleTransforms


The Problem:

You need to dynamically set a variable in a static JavaScript file.

The variable changes with each target environment (test/production etc) and so needs to be set in the app settings (web.config).

Bundling:

MVC4 comes with out of the box bundling capability for static text content. Read for what bundling is and why it is a good idea.

The .net Bundling feature has been designed to be pluggable so you can roll your own Bundler by implementing the IBundleTransform interface.

This is very neat way of addressing the problem of setting a variable in a static file, as you can handle the logic of replacement in your own IBundleTransform class.

The Solution:

1. Add the configuration variable to your app settings of your web.config.










2. Replace the value of the variable being setting in the script with a token e.g. {{ServerAddress}}.











3. Create a bundle Transform that looks for this token and replaces it with the setting from the app settings. We are dealing with the BundleResponse object here.












4. Initialise the bundle in the RegisterBundles method of your BundleConfig in the App_Start folder, specify the virtual path, the files and folders you want to be bundled. Then add a new instance of your IBundleTransform to the list of the bundle's Transforms.











Now, when you make a request to the virtual path (~/Scripts/AllScripts.js) your JavaScript will be returned both minified and with the configuration specific variable included! The replacement logic only gets called once too, as .net will cache the output.

What's more, the MyBundleTransform class is nicely contained and Unit Testable.

Hope this helps!


4 comments:

  1. عند البحث عن شركة توصيل بيارات بالدمام متميزة فإننا يجب أن نخبركم أن شركتنا من أفضل الشركات التي تقوم بعمل عروض على سحب مجاري الدمام بخصم يصل إلى 45% على كافة الخدمات مثل تسليك المجاري وتسليك مواسير الصرف والكثير من الخدمات الأخرى بسعر لا يقارن مع أي شركة أخرى.

    ReplyDelete
  2. تعتبر شركة تنظيف بالرياض كلين الورد من أفضل الشركات الرائدة في مجال التنظيف والتعقيم، حيث تقدم خدمات التنظيف الشاملة والمتكاملة بمنتهى الاحترافية والسرعة دون إحداث فوضى داخل المكان

    ReplyDelete
  3. إذا كنت تبحث عن نقل أثاثك داخل الرياض بتكلفة مناسبة تبدأ من 300 ريال، فهناك من يقدم لك خدمة راقية وهي شركة نقل اثاث بالرياض 300 ريال عمالة فلبينية muhajrrexpress تستحق كل ريال تدفعه

    ReplyDelete