我採用了以下基於約定的方法,對於傳統網絡開發以及移動應用程序和離線HTML5移動應用程序來說,它非常適合我。
約定
- 所有非精縮/完整版JS/CSS腳本命名爲.debug.js或.debug.css擴展。 實施例: global.debug.js和global.debug.css
- 在HTML參考非調試版本到所有JS/CSS的引用:global.js或global.css中
過程
- 我使用自定義的MSBuild任務來縮小JS(使用AjaxMin,但你可以使用YUI壓縮機或其他人)以下的命名約定* .release.js或* .release.css (例如:global.release .js文件)。
- 縮小到* .release.js文件後。我還有一個MSBuild任務調用接受當前配置(調試或發佈)的簡單批處理文件(JS.bat),並將調試(完整源版本)或版本(縮小)版本複製到正常目標。
這裏是樣品的MSBuild任務,我將添加到我的項目文件,以完成縮小,並調用我的批處理文件:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" />
<Target Name="AfterBuild">
<ItemGroup>
<DebugJS Include="**\*.debug.js" />
</ItemGroup>
<AjaxMin SourceFiles="@(DebugJS)" SourceExtensionPattern="\.debug.js$" TargetExtension=".release.js" />
<Exec Command="JS.bat $(Configuration)" />
</Target>
例如,假設:
- 我在調試模式
- 和我有一個global.debug.js文件(我工作的完整源代碼版本)
- 當我構建我的項目時,glo bal.debug.js被縮小到global.release.js
- 由於我處於調試模式配置,global.debug.js將被複制到global.js(這是我的html引用),因此,調試時我將擁有完整源代碼版本
- 如果我切換到發佈模式配置,那麼global.release.js(縮小版本)將被複制到global.js,這就是我想要的發佈/部署到生產。
下面是簡單的批處理腳本(JS.bat),我使用基於傳遞的參數來處理調試的副本或發佈腳本:
@Echo off
REM ----------------------------------------------------------------------------------------
REM <summary>
REM Script used to copy the Debug (or Release) javascript files to the runtime location
REM </summary>
REM <history>
REM <change date="9/22/2010" author="Adam Anderly">Created</change>
REM </history>
REM ----------------------------------------------------------------------------------------
REM Grab the first argument as variable Config (Debug/Release)
SET Config=%~1
REM The loop below is used to get the Length of the Config variable
REM The Length variable is then used in the substring function on Line 22
for /f "tokens=1 delims=:" %%a in (
'^(echo."%Config%"^& [email protected]#^)^|findstr /O /C:"[email protected]#" '
) do set /a Length=%%a-5 + 4
FOR /R %%i IN (*.%Config%.js) DO CALL :REN "%%i"
GOTO :END
:REN
SET File=%~f1
REM Set File2 variable to the runtime filename (minus .debug or .release)
CALL SET File2=%%File:~0,-%Length%%%.js
REM First make sure the destination file is not read-only
IF EXIST "%File2%" ATTRIB /S -R "%File2%"
REM Finally, we copy the current debug|release file to the runtime file
COPY /Y "%File%" "%File2%"
:END
上面的批處理腳本工作遞歸所以你可以有js或css的嵌套文件夾,它仍然有效。
雖然我使用的是MSBuild,但您當然可以使用不同的構建工具將此批處理文件合併到您的過程中(以前我使用NAnt做過相同的操作)。
希望有幫助!
Adam