How can I write a VSCode extension that selects the type of file I am writing in based on my own commands?

72 Views Asked by At

So whenever I create a new react project with npx create-react-app or add a new file to the existing src folder the convention is to have the name of the file capitalized + the .js file extension.

If I look at the status bar in VSCode at the bottom of the screen I can see that the selected language is javascript, vanilla javascript. With vanilla javascript all my css, html and react extensions are not working so I have to manually click on it everytime and select javascript react(.jsx) for them to work properly.

I want to write an extension as that would also be a lovely project that works as the following: if a .js file is starting with a capital letter(as in App.js, Todos.js or Todo.js the selected language is automatically react.

You can see in the status bar that VSCode does not recognize react files as being react files.

I tried looking at the documentation how may I do that but found nothing useful as most of the tutorials are found are not working with VSCode itself but rather implementing stuff from outside to inside VSCode. I have the development workspace set up but I can't find any reference as to how can I do something like that and would need some help.

1

There are 1 best solutions below

0
Mark On BEST ANSWER

As @starball suggested a "file association" can do what you want. In your settings.json (or workspace or folder settings):

  "files.associations": {
    "^[A-Z]*.js": "javascriptreact"
  }

If you want to see one way an extension could do this try this code:

vscode.window.onDidChangeActiveTextEditor(async editor => {
  if (editor) {
    if (editor.document?.languageId === "javascript") {
      const baseName = URI.Utils.basename(editor.document.uri);  // import or require 'vscode-uri'
      const extName = URI.Utils.extname(editor.document.uri);    // import or require 'vscode-uri'

      if (baseName.match(/^[A-Z]/) && extName === '.js') {
        await vscode.languages.setTextDocumentLanguage(editor.document, 'javascriptreact');
     }
  }
}