Search and replace in Javascript before bundling

Summary

Is there any way to make the bundling and minification process in an ASP.NET MVC-application perform a "search and replace" inside the script files before it minifies them?

Background

I have some widgets defined in Javascript-files that contain words which need to be translated into different languages, depending on the current user's language. Since the javascript-files are minified into ScriptBundles by MVC, is it possible to hook into this build process? Ideally, we could use it to create localized script bundles, where the bundling process performs the search/replace inside the scripts before they are minified.

I would like to avoid manually creating separate javascript-files per language, since it would make it difficult to maintain. The same goes for a client-side dictionary that the widgets would pull text from; we already have problems with javascript performance, and do not want to add another layer of front-end calculations.

Answers:

Answer

As Vladimir said, you can create your own Bundle transformation, simply implementing IBundleTransform. I have written a blog post about bundling and minifying Coffeescripts that can point you in the right direction : http://tallmaris.com/advanced-bundling-and-minification-of-coffeescripts-in-mvc4/

In summary, create a custom transform like this:

public class MultiLanguageBundler : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        foreach (var file in response.Files)
        {
            using (var reader = new StreamReader(file.FullName))
            {
                // "ReplaceLanguageStrings" contains the search/replace logic
                compiled += ReplaceLanguageStrings(reader.ReadToEnd());
                reader.Close();
            }
        }
        response.Content = compiled;
        response.ContentType = "text/javascript";
    }
}

Then in your BundleConfig:

var myBundle = new Bundle("~/Scripts/localised")
                   .Include("~/JsToLocalise/*.js"); //your JS location here, or include one by one if order is important.
myBundle.Transforms.Add(new MultiLanguageBundler());
myBundle.Transforms.Add(new JsMinify());
bundles.Add(myBundle);

You may need to tweak a few things but let me know if it helps you.

Answer

Implement IBundleTransform interface. Example can be found here.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.