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!
Fantastic example thanks!
ReplyDelete