Is there a way to trim a TM_FILENAME beyond using

2019-08-19 00:40发布

问题:

I am trying to create a snippet for a redux container file that takes an import of some react file of the same base name. TM_FILENAME_BASE works great for removing the .js from the file name but in this case, my component file's extension is fun-thing.component.js and the container will follow suit with an extension that is fun-thing.container.js.

The Regex I am using to select everything before the first period is ^([^.]+)

  "Redux Container": {
    "prefix": "rc",
    "body": [
      "// @flow",
      "import { connect } from 'react-redux';",
      "import { ${TM_FILENAME/^([^.]+)/${1:/pascalcase}/}Component } from './${TM_FILENAME/^([^.]+)/$1/}.component';",
      "",
      "const mapStateToProps = (state) => ({});",
      "",
      "const mapDispatchToProps = {};",
      "",
      "export const ${TM_FILENAME/^([^.]+)/${1:/pascalcase}/} = connect(",
      "  mapStateToProps,",
      "  mapDispatchToProps",
      ")(${TM_FILENAME/^([^.]+)/${1:/pascalcase}/}Component);"
    ],
    "description": "Creates a normal container for a normal component"
  }

expected

// @flow
import { connect } from 'react-redux';
import { FunThingComponent } from './fun-thing.component';
...

actual

// @flow
import { connect } from 'react-redux';
import { FunThing.container.jsComponent } from './FunThing.container.js.component';
...

As you can see, it is not omitting the file extensions.

回答1:

Both of these work:

  "import { ${TM_FILENAME/^([^.]+).*/${1:/pascalcase}/}Component } from './${TM_FILENAME/^([^.]+).*/$1/}.component';",

  "import { ${TM_FILENAME/(.*?)\\..+/${1:/pascalcase}/}Component } from './${TM_FILENAME/(.*?)\\..+/$1/}.component';"

With the vscode snippet transforms if you want to exclude part of the variable as you want, removing the .component.js from the filename, then that part of the variable must be accounted for in the regex - hence (.*?)\\..+.

Otherwise that "unseen" part of the variable just passes through.

So your regex ^([^.]+) was accurately capturing the part of the filename before the first . but then the rest of the variable was "passing through" unmodified.

You can see this more clearly with this example:

"import { ${TM_FILENAME//${1:/pascalcase}/}Component }

that yields:

import { fun-thing.component.jsComponent }

so the entire filename is passed through although none of it is captured.

${someVariable/everything To Be Transformed/what To Do To the previous/}

if it isn't in the "everything to be transformed" part nothing happens to it.