我采用了以下基于约定的方法,对于传统网络开发以及移动应用程序和离线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