JS/CSS緩存殺手——VS插件


背景

   前些天去考科目二,感覺經歷了一場不是高考卻勝似高考的考試(10年前的5分之差, 還是難以釋懷)!

     一行八人,就我學的時間最少(4天,8人一輛車),教練都覺得我肯定還得再來一次!

   靠着運氣和信念,驚險的通過了側方停車和倒車入庫,終於還是撫慰了一下10年前那顆年輕的心!

    

 

   ——————————感慨完畢,回歸主題——————————

 

       終於修改完了客戶提交的bugs,發布、更新、測試、郵件通知,悠哉悠哉的瀏覽博客園...然后客戶來了...

   客戶:我提的需求怎么都沒修改,這個按鈕顏色也沒變,點擊效果還是以前的,那個界面也沒修改...!@#$%^&*...

    我:我這里都正常的,截圖給你看下...

   客戶:要不你遠程看下什么問題。

    我:哦,瀏覽器緩存沒有更新,你強制刷新下

   客戶:怎么強制刷新?

    我:ctrl+f5,手機上...!@#$%^&*...

   客戶:(° ?°)~@

  

       ——————————以上對話來源生活,如有雷同,實屬正常——————————

 

        每次更新后,總會產生這樣的對話,每次解釋半天都是無功而返,最后還是一個個的給每個js,css文件加上 ?v=111 這樣的字樣,勞心又費神,還不討好。

    然后引入combres 以為可以萬事大吉了,增加js和css引用麻煩,每次去修改配置也是麻煩,同事也都不願意用了。

    最后,只能要求大家修改時都添加 ?v=xxx 的字樣,律己容易律人難,再則操作確實也不方便,大家更不願意弄了。

    你不去修改,問題就在那里,只增不減...

    

快捷輸入

  后來發現VS有這么一個功能,可以把代碼片段拖到工具欄,點擊可以自動快捷輸入,效果如下,用起來非常方便,當時就想如果js和css版本號也可以有快捷的輸入,大家也會更願意去操作吧,但是因為這個內容是固定的,所以用起來還是不太方便。於是,路漫漫其修遠兮,吾將上下而求索!

     

   

  

VS插件開發---自己動手,豐衣足食

   直到看到這個 《強迫症的福利——我的第一個VS插件,對using排序!》 文章,我就知道了:只要你想,就有可能。至於安裝 VisualStudio SDK,創建項目之類的,前面的文章已經講得蠻多了。有興趣的可以移步前面的文章鏈接哈!

   配置要修改的不多,基本就是圖標、快捷鍵、菜單名稱等。以下是我的完整配置文件

<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!--  This is the file that defines the actual layout and type of the commands.
        It is divided in different sections (e.g. command definition, command
        placement, ...), with each defining a specific set of properties.
        See the comment before each section for more details about how to
        use it. -->

  <!--  The VSCT compiler (the tool that translates this file into the binary
        format that VisualStudio will consume) has the ability to run a preprocessor
        on the vsct file; this preprocessor is (usually) the C++ preprocessor, so
        it is possible to define includes and macros with the same syntax used
        in C++ files. Using this ability of the compiler here, we include some files
        defining some of the constants that we will use inside the file. -->

  <!--This is the file that defines the IDs for all the commands exposed by VisualStudio. -->
  <Extern href="stdidcmd.h"/>

  <!--This header contains the command ids for the menus provided by the shell. -->
  <Extern href="vsshlids.h"/>

  <!--The Commands section is where commands, menus, and menu groups are defined.
      This section uses a Guid to identify the package that provides the command defined inside it. -->
  <Commands package="guidfillVersionPackage">
    <!-- Inside this section we have different sub-sections: one for the menus, another
    for the menu groups, one for the buttons (the actual commands), one for the combos
    and the last one for the bitmaps used. Each element is identified by a command id that
    is a unique pair of guid and numeric identifier; the guid part of the identifier is usually
    called "command set" and is used to group different command inside a logically related
    group; your package should define its own command set in order to avoid collisions
    with command ids defined by other packages. -->

    <!-- In this section you can define new menu groups. A menu group is a container for
         other menus or buttons (commands); from a visual point of view you can see the
         group as the part of a menu contained between two lines. The parent of a group
         must be a menu. -->
    <Groups>
      <Group guid="guidfillVersionPackageCmdSet" id="MyMenuGroup" priority="0x0600">
        <Parent guid="guidSHLMainMenu" id="IDM_VS_MENU_TOOLS"/>
      </Group>
    </Groups>

    <!--Buttons section. -->
    <!--This section defines the elements the user can interact with, like a menu command or a button
        or combo box in a toolbar. -->
    <Buttons>
      <!--To define a menu group you have to specify its ID, the parent menu and its display priority.
          The command is visible and enabled by default. If you need to change the visibility, status, etc, you can use
          the CommandFlag node.
          You can add more than one CommandFlag node e.g.:
              <CommandFlag>DefaultInvisible</CommandFlag>
              <CommandFlag>DynamicVisibility</CommandFlag>
          If you do not want an image next to your command, remove the Icon node /> -->
      <Button guid="guidfillVersionPackageCmdSet" id="fillVersionId" priority="0x0100" type="Button">
        <Parent guid="guidfillVersionPackageCmdSet" id="MyMenuGroup" />
        <Icon guid="guidImages" id="bmpPic1" />
        <Strings>
          <ButtonText>設置版本號</ButtonText>
        </Strings>
      </Button>
      
    </Buttons>

    <!--The bitmaps section is used to define the bitmaps that are used for the commands.-->
    <Bitmaps>
      <!--  The bitmap id is defined in a way that is a little bit different from the others:
            the declaration starts with a guid for the bitmap strip, then there i sthe resource id of the
            bitmap strip containing the bitmaps and then there are the numeric ids of the elements used
            inside a button definition. An important aspect of this declaration is that the element id
            must be the actual index (1-based) of the bitmap inside the bitmap strip. -->
      <Bitmap guid="guidImages" href="Resources\fillVersion.png" usedList="bmpPic1"/>
    </Bitmaps>
   
  </Commands>
  <KeyBindings>
    <!-- 設置快捷鍵 alt+J. -->
  <KeyBinding guid="guidfillVersionPackageCmdSet" id="fillVersionId" editor="guidVSStd97" key1="J" mod1="ALT" />
  </KeyBindings>
  <Symbols>
    <!-- This is the package guid. -->
    <GuidSymbol name="guidfillVersionPackage" value="{67c49ffd-7eca-4805-9b45-a837fb03a08c}" />

    <!-- This is the guid used to group the menu commands together -->
    <GuidSymbol name="guidfillVersionPackageCmdSet" value="{af86a8d5-ac26-40b6-be11-0fcf3d9bd974}">
      <IDSymbol name="MyMenuGroup" value="0x1020" />
      <IDSymbol name="fillVersionId" value="0x0100" />
    </GuidSymbol>

    <GuidSymbol name="guidImages" value="{da500753-6754-4737-82c4-2b65d5e9ad59}" >
      <IDSymbol name="bmpPic1" value="1" />
      <IDSymbol name="bmpPic2" value="2" />
      <IDSymbol name="bmpPicSearch" value="3" />
      <IDSymbol name="bmpPicX" value="4" />
      <IDSymbol name="bmpPicArrows" value="5" />
      <IDSymbol name="bmpPicStrikethrough" value="6" />
    </GuidSymbol>
  </Symbols>
</CommandTable>

  

  搭好項目,配置完成,我們開始上菜了。

小菜第一版

  我們知道菜單的邏輯都在 fillVersion.cs  -》MenuItemCallback 中實現

  第一版功能非常簡單,就是簡單的輸入 ?v=yyyyMMddss,表面上已經實現了我的想法,確實也比原來方便多了,只要按下快捷鍵就完成原來多次輸入的效果,代碼如下

 

1 var dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE;
2 var selection = dte.ActiveDocument.Selection as TextSelection;//當前文檔中選中的部分
3 if (selection == null)
4 { 
5    return;
6 }
8 string versionstr = "?v=" + DateTime.Now.ToString("yyyyMMddss");
9 selection.Insert(versionstr, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);//重新寫入文檔

 

  

   效果如下:

  

 

  但是問題來了:

  A、光標一定要定位到文件名后面,這完全是在制造麻煩么?

  B、我要同時給幾個js添加版本號怎么辦?一個個添加?這還是在制造麻煩么?

  C、我要同時給js和css添加版本號又怎么辦呢?

  ...

  帶着這些疑問,我開始了新的起航。

 

小菜最終版

   在解決第一版提出的問題,首先我們得解析我們選中的內容,隨便百度一下,我就發現了 HtmlAgilityPack,后面的工作就簡單了,便利選中 script和link 標簽,獲取 href,src 屬性,加個?v=yyyyMMddss 就OK了。

   這個版本,我們可以直接多個標簽批量設置版本號了,操作就更方便了。使用方便了,同事自然就想用了,都不用我去要求了。

   直接上代碼吧,大家一看就了然了,沒有注釋哈,代碼就是最好的注釋了。

   

 1 var dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE;
 2 var selection = dte.ActiveDocument.Selection as TextSelection;//當前文檔中選中的部分
 3 if (selection == null)
 4 {
 5     return;
 6 }
 7 
 8  HtmlDocument doc = new HtmlDocument();
 9  doc.LoadHtml(selection.Text);
10 
11  HtmlNodeCollection script = doc.DocumentNode.SelectNodes("//script");
12  HtmlNodeCollection link = doc.DocumentNode.SelectNodes("//link");
13 
14  string newcontent = "";
15  string versionstr = "?v=" + DateTime.Now.ToString("yyyyMMddss");
16 
17  if (link != null)
18  {
19                 foreach (HtmlNode categoryNode in link)
20                 {
21                     string href = categoryNode.Attributes["href"].Value;
22                     if (href.IndexOf("?") > 0)
23                     {
24                         href = href.Substring(0, href.IndexOf("?"));
25                     }
26                     href += versionstr;
27                     newcontent += "<link type=\"text/css\" rel=\"stylesheet\" href=\"" + href + "\" />\r\n";
28                 }
29             }
30 
31 
32             if (script != null)
33             {
34                 foreach (HtmlNode categoryNode in script)
35                 {
36                     string src = categoryNode.Attributes["src"].Value;
37                     if (src.IndexOf("?") > 0)
38                     {
39                         src = src.Substring(0, src.IndexOf("?"));
40                     }
41                     src += versionstr;
42                     newcontent += "<script src=\"" + src + "\"></script>\r\n";
43                 }
44 
45             }
46 
47             if (newcontent.Length == 0)
48             {
49                 newcontent = versionstr;
50             }
51 
52 selection.Insert(newcontent, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);//重新寫入文檔

 

   

  再上幾張最后的效果圖,有圖有真像,后面還有代碼哦(至於最后用HJ這個圖標,就是為了給媳婦邀功 \\*^o^*// )。

  

 

  

              (選擇一行)           

  

                          (選擇多行,包含link,script標簽)                                                                                                     

                

結語

  雖然這個插件功能非常簡單,但是整理這個開發的過程還是用了好幾個晚上。個人覺得還是蠻實用的(至少對我們開發,還是非常有幫助的),特來分享給大家(后面有安裝文件和源碼)。

  覺得有幫助呢,動動手指點個贊,圖個高興;覺得寫得不好,也接受拍磚哈;寫得不正確的地方,請不吝賜教下哈,共同進步!

  安裝文件,點擊下載(VS2015開發的,不能安裝的話,自行編譯哈)

  源代碼,壓縮后還有11M,只能上傳CSDN了,免積分哦。點擊下載

 

   成為一名優秀的程序員!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM