Search and replace in Javascript before bundling

折月煮酒 提交于 2019-12-04 05:19:26

问题


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.


回答1:


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.




回答2:


Implement IBundleTransform interface. Example can be found here.



来源:https://stackoverflow.com/questions/18509506/search-and-replace-in-javascript-before-bundling

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