Search and replace in Javascript before bundling

前端 未结 2 1517
走了就别回头了
走了就别回头了 2021-01-25 01:30

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

相关标签:
2条回答
  • 2021-01-25 02:06

    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.

    0 讨论(0)
  • 2021-01-25 02:22

    Implement IBundleTransform interface. Example can be found here.

    0 讨论(0)
提交回复
热议问题