【问题标题】:VS Code user snippet convert filename(kebab case) to snake caseVS Code 用户代码段将文件名(kebab 案例)转换为蛇案例
【发布时间】:2022-08-19 02:36:24
【问题描述】:

我的文件名:company-news-model.js

我希望它变成company_news

    标签: visual-studio-code vscode-snippets


    【解决方案1】:

    如果你必须把它放在一个 sn-p 中,试试这个:

    "filePath to snake": {
      "prefix": "2Snake",
      "body": [
    
        "${TM_FILENAME_BASE/-([^-]*)(?=-)|(-.*)$/${1:+_}$1/gm}"
    
         // gm regex flags are both necessary
         // just put a ; at the end (before the closing quote) if you want one there
        
      ]
    }
    

    它适用于任何长度的文件名,如 a-b-c-d.js 等。

    使用您的示例文件:company-news-model.js

    TM_FILENAME_BASEcompany-news-model

    -([^-]*)(?=-) :仅匹配 -news,捕获组 1

    (-.*)$ :匹配名称的结尾,-model 在第 2 组中,我们不会在替换中使用

    请注意,company 永远不会匹配,只要在最终结果中可以接受它,您就不需要匹配,就是这样。

    替换变换:

    ${1:+_} :这意味着如果有一个组 1,插入一个_
    $1 :插入组 1

    所以company 失败,因为它永远不会匹配,然后是_ 和组1。然后因为它是一个全局正则表达式,所以再添加_ 和找到的组1。

    请注意,company-news-model.component.js 之类的文件将按照我的预期转换为 company_news


    更强大的方法可以转换任何情况下的文件名到 kebab-case - 但这将是一个键绑定而不是一个 sn-p。您将需要扩展名Find and Transform(由我编写)。

    进行此键绑定(在您的 keybindings.json 中):

     {
      "key": "alt+s",                  // whatever keybinding you want 
      "command": "findInCurrentFile",
      "args": {
        // inserted at the cursor(s), if cursor is not in or against a word
        "replace": "${fileBasenameNoExtension}",
        "postCommands": ["editor.action.transformToKebabcase", "cancelSelection"]
      },
    }
    

    插入、选择fileBasenameNoExtension,然后在其上运行命令editor.action.transformToKebabcase

    【讨论】:

    • 是否可以将 kebab-case 中的文件名从任何其他情况转换?
    • @MightyCoderX 是的,如果键绑定没问题(而不是 sn-p)。请参阅添加到答案末尾的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多