How can I automatically compress and minimize JavaScript files in an ASP.NET MVC app?

后端 未结 8 2131
悲&欢浪女
悲&欢浪女 2020-12-22 19:10

So I have an ASP.NET MVC app that references a number of javascript files in various places (in the site master and additional references in several views as well).

<
8条回答
  •  没有蜡笔的小新
    2020-12-22 19:34

    Actually there is a much easier way using Web Deployment Projects (WDP). The WDP will manage the complexities of the aspnet__compiler and aspnet__merge tool. You can customize the process by a UI inside of Visual Studio.

    As for the compressing the js files you can leave all of your js files in place and just compress these files during the build process. So in the WDP you would declare something like this:

    
       REMOVE CONTENT HERE FOR WEB
    
    
    
    
      
        $(BuildDependsOn);
        CompressJavascript
      
    
    
    
      
        <_JSFilesToCompress Include="$(OutputPath)Scripts\**\*.js" />
      
      
      
    
    
    

    This uses the JSCompress MSBuild task from the MSBuild Community Tasks which I think is based off of JSMin.

    The idea is, leave all of your js files as they are (i.e. debuggable/human-readable). When you build your WDP it will first copy the js files to the OutputPath and then the CompressJavascript target is called to minimize the js files. This doesn't modify your original source files, just the ones in the output folder of the WDP project. Then you deploy the files in the WDPs output path, which includes the pre-compilied site. I covered this exact scenario in my book (link below my name).

    You can also let the WDP handle creating the Virtual Directory as well, just check a checkbox and fill in the name of the virtual directory.

    For some links on MSBuild:

    • Inside MSBuild
    • 7 Steps To MSBuild
    • MSDN MSBuild Docs

    Sayed Ibrahim Hashimi

    My Book: Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build

提交回复
热议问题