Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version 2 stop working with nvim lsp #3925

Closed
RayGuo-ergou opened this issue Mar 2, 2024 · 142 comments
Closed

Version 2 stop working with nvim lsp #3925

RayGuo-ergou opened this issue Mar 2, 2024 · 142 comments

Comments

@RayGuo-ergou
Copy link
Contributor

RayGuo-ergou commented Mar 2, 2024

Update: check readme.


tldr:
local mason_registry = require('mason-registry')
local ts_plugin_path = mason_registry.get_package('vue-language-server'):get_install_path() .. '/node_modules/@vue/language-server/node_modules/@vue/typescript-plugin'

local servers = {
  tsserver = {
    init_options = {
      plugins = {
        {
          name = '@vue/typescript-plugin',
          location = ts_plugin_path,
          -- If .vue file cannot be recognized in either js or ts file try to add `typescript` and `javascript` in languages table.
          languages = { 'vue' },
        },
      },
    },
    filetypes = { 'typescript', 'javascript', 'javascriptreact', 'typescriptreact', 'vue' },
  },
  volar = {},
}

local mason_lspconfig = require('mason-lspconfig')

-- Auto cmd (LspAttach) to setup keybind, codelens, and formatting stuff
-- I assume everyone should have this configured already but just for reference
-- @see https://github.com/RayGuo-ergou/dotfiles/blob/cdf866790b1daa27444bd9991025740c8eb74c5b/nvim/lua/ergou/util/lsp.lua#L43
Util.lsp.lsp_autocmd()

local capabilities = vim.lsp.protocol.make_client_capabilities()
-- If you need cmp
capabilities = vim.tbl_deep_extend('force', capabilities, require('cmp_nvim_lsp').default_capabilities())
mason_lspconfig.setup({
ensure_installed = vim.tbl_keys(servers),
handlers = {
    function(server_name)
    local server = servers[server_name] or {}
    server.capabilities = vim.tbl_deep_extend('force', {}, capabilities, server.capabilities or {})
    require('lspconfig')[server_name].setup(server)
    end,
},
})

Hi,

I am having issue to run volar@2.0.1 with neovim lsp.

cmd: vue-language-server --stdio

With 1.8.27:
image
image
image

With 2.0.1:
image
image
image

@RayGuo-ergou RayGuo-ergou changed the title Version 2 not working with nvim lsp Version 2 stop working with nvim lsp Mar 2, 2024
@johnsoncodehk
Copy link
Member

After 2.0, typescript support is fully implemented through typescript plugin. For IDEs other than VSCode, you need to install @vue/typescript-plugin(https://www.npmjs.com/package/@vue/typescript-plugin) separately, which will work with @vue/language-server.

I'm not sure how nvim configures the typescript plugin, if nvim can't configure it, you need to install @vue/typescript-plugin to the project or globally, and then configure it in tsconfig.

{
    "compilerOptions": {
        "plugins": [{ "name": "@vue/typescript-plugin" }]
    }
}

@RayGuo-ergou

This comment was marked as outdated.

@BitInByte
Copy link

Hey, I'm also facing the exact same issues. None of the lsp functionality works, even though it is able to attach successfully. I can also say that previously, the last version I had before updating was working without any issue

@adriaanbaelus
Copy link

Same here, the language server is running and attached to my vue file, but completely nonfunctional. Like @RayGuo-ergou, I've downgraded to 1.8.27 for now.

@johnsoncodehk I'm not clear on how the vue language server works, but for most neovim users, volar is installed globally with Mason, a sort of package manager for language servers. It installs a specific version of @vue/language-server in a specific location.
The next step is configuring the language server, which is usually done using nvim-lspconfig. In practice, it runs (the previously installed) @vue/language-server/bin/vue-language-server.js --stdio and passes the typescript tsdk as initializationOptions.
I'm guessing the default configuration there no longer works with the 2.0 release, but I have no idea what configuration is needed to get it right.
Is there any documentation on how to get the 2.x language server configured and running?

@WhyNotHugo
Copy link
Contributor

Upgrading the LSP to 2.0.3 on neovim works for me. Note that the 2.0.0 release was broken, so be sure to install the latest patch version.

To confirm that the LSP is working, I opened a SFC and removed a <, at which point the LSP indicated an error in the corresponding end tag.

@WhyNotHugo
Copy link
Contributor

I have installed @vue/typescript-plugin, but TypeScript support won't work for me.

Is it loaded automatically by the LSP? Any documentation/guide/example would be most welcome.

@WhyNotHugo
Copy link
Contributor

packages/language-server/lib/types.ts defines initialisation options:

export type VueInitializationOptions = InitializationOptions & {
	typescript: {
		tsdk: string;
	}
	vue?: {
		/**
		 * @example ['vue1', 'vue2']
		 */
		additionalExtensions?: string[];
	};
};

The InitializationOptions interface is defined in https://github.com/volarjs/volar.js in packages/language-server/lib/types.ts:

export interface InitializationOptions {
	l10n?: {
		location: string; // uri
	};
	diagnosticModel?: DiagnosticModel;
	maxFileSize?: number;
	/**
	 * Extra semantic token types and modifiers that are supported by the client.
	 */
	semanticTokensLegend?: vscode.SemanticTokensLegend;
	codegenStack?: boolean;
}

The only relevant thing that I see is the typescript/tsdk field, but that one is not new, so I don't think that it is necessary. I don't see any obvious way to specify plug-ins, so maybe they don't need to be explicitly registered?

@RayGuo-ergou

This comment was marked as outdated.

@WhyNotHugo
Copy link
Contributor

I have not tried a javascript project yet. I tried a typescript project, and error diagnostics only show up for the html template portion, but not for typescript code.

@jblyberg
Copy link

jblyberg commented Mar 3, 2024

I was able to get everything working with 2.0.3. Here is my config (note, I use neoconf to tell lspconfig I'm using a volar project). I am also using typescript-tools instead of tsserver.

{
    "neovim/nvim-lspconfig",
    dependencies = {
      "pmizio/typescript-tools.nvim",
    },
    opts = {
      servers = {
        tsservercontext = {},
      },

      setup = {
        tsservercontext = function(_, opts)
          local neoconf = require("neoconf")
          local lspconfig = require("lspconfig")

          if neoconf.get("is-volar-project") then
            lspconfig["volar"].setup({
              server = opts,
              settings = {},
            })

            require("typescript-tools").setup({
              server = opts,
              settings = {
                tsserver_plugins = {
                  "@vue/typescript-plugin",
                },
              },
              filetypes = {
                "javascript",
                "typescript",
                "vue",
              },
            })
          else
            require("typescript-tools").setup({
              server = opts,
            })
          end

          return true
        end,
      },
    },
  }

Note specifically:

tsserver_plugins = {
  "@vue/typescript-plugin",
}

This works fine, however, volar still tries to fetch definitions in .vue files, so I get a "No information available" notice.

@chaozwn
Copy link

chaozwn commented Mar 4, 2024

I was able to get everything working with 2.0.3. Here is my config (note, I use neoconf to tell lspconfig I'm using a volar project). I am also using typescript-tools instead of tsserver.

{
    "neovim/nvim-lspconfig",
    dependencies = {
      "pmizio/typescript-tools.nvim",
    },
    opts = {
      servers = {
        tsservercontext = {},
      },

      setup = {
        tsservercontext = function(_, opts)
          local neoconf = require("neoconf")
          local lspconfig = require("lspconfig")

          if neoconf.get("is-volar-project") then
            lspconfig["volar"].setup({
              server = opts,
              settings = {},
            })

            require("typescript-tools").setup({
              server = opts,
              settings = {
                tsserver_plugins = {
                  "@vue/typescript-plugin",
                },
              },
              filetypes = {
                "javascript",
                "typescript",
                "vue",
              },
            })
          else
            require("typescript-tools").setup({
              server = opts,
            })
          end

          return true
        end,
      },
    },
  }

Note specifically:

tsserver_plugins = {
  "@vue/typescript-plugin",
}

This works fine, however, volar still tries to fetch definitions in .vue files, so I get a "No information available" notice.

My thoughts are the same as yours: typescript-tools.nvim is used for handling ts and js files, while volar is used for handling vue files. However, it seems that there are currently issues with volar.

@RayGuo-ergou

This comment was marked as outdated.

@WhyNotHugo
Copy link
Contributor

Oh, I had assumed that "typescript plugin" meant "a plugin that adds typescript support to this language server".

Did I misunderstand this and "typescript plugin" is a actually plugin for tsserver that adds vue support to it?

I'm a bit confused about volar's role if that's the case. If the typescript plugin gives tsserver the ability to handle vue code, why do I still need to keep around volar?

@jblyberg
Copy link

jblyberg commented Mar 4, 2024

I'm a bit confused about volar's role if that's the case. If the typescript plugin gives tsserver the ability to handle vue code, why do I still need to keep around volar?

I believe that volar provides language server support inside template tags and is also required by the vue typescript plugin.

@WhyNotHugo
Copy link
Contributor

WhyNotHugo commented Mar 4, 2024

I installed @vue/typescript-plugin together with tsserver, but it still won't yield error diagnostics for a SFC file.

I'm taking a pretty straightforward approach here:

  tsserver = {
    -- I installed @vue/typescript-plugin inside this container:
    cmd = lsp_containers.command("tsserver"),
    settings = {
      tsserver_plugins = {
        "@vue/typescript-plugin",
      },
    },
    filetypes = {
      "javascript",
      "typescript",
      "vue",
    },
  },

For regular typescript files, tsserver can't seem to resolve those SFC. E.g.: for line import Header from "./components/Header.vue";, it shows:

Cannot find module './components/Header.vue' or its corresponding type declarations.

@chaozwn
Copy link

chaozwn commented Mar 4, 2024

I got the lsp working with only typscript-tool plugin ( so no volar notify upon hover ). Huge thanks to @jblyberg.

image image image

My config:

      mason_lspconfig.setup({
        ensure_installed = vim.tbl_keys(servers),
        handlers = {
          function(server_name)
            local server = servers[server_name] or {}
            server.on_attach = on_attach
            server.capabilities = vim.tbl_deep_extend('force', {}, capabilities, server.capabilities or {})
            -- inherit my volar settings, you can just add vue to the `typescript-tools` filetypes.
            if server_name == 'volar' then
              require('typescript-tools').setup(server)
            else
              require('lspconfig')[server_name].setup(server)
            end
          end,
        },
      })

The @vue/typescript-plugin need to be defined in tsconfig.json as Johnson mentioned. ( make sure you have it installed)

{
    "compilerOptions": {
        "plugins": [{ "name": "@vue/typescript-plugin" }]
    }
}

image
We have the same configuration, so why am I getting a tsserver error?

@WhyNotHugo
Copy link
Contributor

Does @vue/typescript-plugin need to be installed with tsserver or within the current project's node_modules?

@chaozwn
Copy link

chaozwn commented Mar 4, 2024

Does @vue/typescript-plugin need to be installed with tsserver or within the current project's node_modules?

you must use typescript-tools.nvim replace tsserver.

@jblyberg
Copy link

jblyberg commented Mar 4, 2024

Does @vue/typescript-plugin need to be installed with tsserver or within the current project's node_modules?

What I've found (and I spent way too much time on this yesterday) is that tsserver doesn't (at least for me) load the vue typescript plugin. You can try for yourself. Look at the tsserver docs https://github.com/typescript-language-server/typescript-language-server/blob/master/docs/configuration.md .. You can specify plugin settings under initializationOptions but that doesn't seem to work. This issue seems to indicate that others have trouble with that setting, however, and I couldn't get tsserver to load that plugin. the typescript-tools package is more explicit about how to load tsconfig plugins and works, so I went with that.

@WhyNotHugo
Copy link
Contributor

Sounds like loading plugins via tsserver is problematic or non-trivial. But the devs here must have figured out a way to load the plugin to test it and use it themselves. typescript-tools.nvim is neovim-specific, I don't think they'd target that exclusively.

@WhyNotHugo
Copy link
Contributor

Oh, actually, what I'm using is typescript-language-server, not tsserver.

@WhyNotHugo
Copy link
Contributor

@gegoune
Copy link

gegoune commented Mar 4, 2024

you must use typescript-tools.nvim replace tsserver.

Are you saying that there currently is no way to make it work with tsserver or that above configuration targets typescript-tools.nvim?

I would rather not switch to software which warns about its early beta stage just yet.

@jblyberg
Copy link

jblyberg commented Mar 4, 2024

I think it's entirely probable that I am just not initializing tsserver correctly--which I think is a documentation issue. As @johnsoncodehk said, non-VSCode editors have to handle this manually.

@jblyberg
Copy link

jblyberg commented Mar 4, 2024

Apparently the location field is also required when defining plugins: https://github.com/typescript-language-server/typescript-language-server/blob/b224b878652438bcdd639137a6b1d1a6630129e4/docs/configuration.md?plain=1#L27-L31

Setting the location did not work for me either. Check out this issue which suggests that you can also just put anything in there like so:

plugins = {
  {
    name = "anything";
    location = "anything";
  };
};

That did not work either.

@WhyNotHugo
Copy link
Contributor

WhyNotHugo commented Mar 4, 2024

I made it work! 🎉

  tsserver = {
    cmd = lsp_containers.command("tsserver"),
    init_options = {
      plugins = {
        {
          name = "@vue/typescript-plugin",
          location = "/usr/local/lib/node_modules/@vue/typescript-plugin",
          languages = {"typescript", "vue"},
        },
      },
    },
    filetypes = {
      "javascript",
      "typescript",
      "vue",
    },
  },

This shows error diagnostics on the <script> portion of SFC files.

@chaozwn
Copy link

chaozwn commented Mar 4, 2024

I got the lsp working with only typscript-tool plugin ( so no volar notify upon hover ). Huge thanks to @jblyberg.

image image image

My config:

      mason_lspconfig.setup({
        ensure_installed = vim.tbl_keys(servers),
        handlers = {
          function(server_name)
            local server = servers[server_name] or {}
            server.on_attach = on_attach
            server.capabilities = vim.tbl_deep_extend('force', {}, capabilities, server.capabilities or {})
            -- inherit my volar settings, you can just add vue to the `typescript-tools` filetypes.
            if server_name == 'volar' then
              require('typescript-tools').setup(server)
            else
              require('lspconfig')[server_name].setup(server)
            end
          end,
        },
      })

The @vue/typescript-plugin need to be defined in tsconfig.json as Johnson mentioned. ( make sure you have it installed)

{
    "compilerOptions": {
        "plugins": [{ "name": "@vue/typescript-plugin" }]
    }
}

null-ls format working properly?

@jblyberg
Copy link

jblyberg commented Mar 4, 2024

I made it work! 🎉
This shows error diagnostics on the <script> portion of SFC files.

Interesting. I had not tried installing the plugin globally. I'd rather not have to do that but I'll give it a shot.

@nevenduranec
Copy link

How does volar resolve alises in jsconfig.json? On version < 2 it works but on latest v2 it's not working (monorepo, the jsconfig.js is not in the project top level root) (neovim 0.9.5).
Edit:
Goto definition and lsp references don't work as well (gd when the cursor is on the workd axios for example import axios from 'axios').

Are you using auto import and vue component from unplugin?

No, it's a plain old vue 2 project, no typescript at all.

@wcheek
Copy link

wcheek commented Mar 29, 2024

There is some official documentation for what config is necessary for fixing this issue. Seems like the volar team didn't give their community dependents much of a heads-up...

TLDR. I've added this to my init.lua and solved the issue for "@vue/language-server": "^2.0.7"

local lspconfig = require("lspconfig")

-- Allows volar to run embedded tsserver
lspconfig.volar.setup({
    filetypes = { 'typescript', 'javascript', 'javascriptreact', 'typescriptreact', 'vue' },
  init_options = {
    vue = {
      hybridMode = false,
    },
  },
})

Edit: Actually, this gave me some LSP capabilities but not all.

I found another suggested config in nvim-lspconfig documentation that seems to be working. You will have to install @vue/typescript-plugin globally and edit the location for your case.

-- init.lua
local lspconfig = require("lspconfig")

lspconfig.volar.setup({})
lspconfig.tsserver.setup({
  init_options = {
    plugins = {
      {
        name = "@vue/typescript-plugin",
        location = "C:\\Users\\wcheek\\AppData\\Roaming\\npm\\node_modules\\@vue\\typescript-plugin\\",
        languages = { "javascript", "typescript", "vue" },
      },
    },
  },
  filetypes = {
    "javascript",
    "typescript",
    "vue",
  },
})

@Jtcruthers
Copy link

I have a bunch of projects with both Vue2 and Vue3 and got the default tsserver working well with Mason and Neoconf. I installed tsserver, volar, and vuels (vetur) with Mason.

In all of my Vue2 projects, I disable both tsserver and volar via the local .neoconf.json:

{
  "lspconfig": {
    "tsserver": false,
    "volar": false
  }
}

Then in all of my Vue3 projects, I disable vuels and set a boolean to add the plugin in my local .neoconf.json:

{
  "is-volar-project": true,
  "lspconfig": {
    "vuels": false
  }
}

I globally install the latest @vue/typescript-plugin.

Then in my neovim lua config, I use mason-lspconfig to config tsserver with the plugin:

require("mason-lspconfig").setup_handlers {
  function(server_name)
    require("lspconfig")[server_name].setup {
      capabilities = lsp_capabilities,
    }
  end,
   ["tsserver"] = function()
    local neoconf = require("neoconf")

    local init_options = {}
    if neoconf.get("is-volar-project") then
      init_options = {
        plugins = {
          {
            name = "@vue/typescript-plugin",
            location = "/path/to/global/node_modules/@vue/typescript-plugin",
            languages = {"javascript", "typescript", "vue"},
          },
        },
      }
    end

    require("lspconfig").tsserver.setup {
      filetypes = { "vue", "javascript", "javascriptreact", "javascript.jsx", "typescript", "typescriptreact", "typescript.tsx" },
      compilerOptions = {
        noErrorTruncate = true
      },
      init_options = init_options,
    }
  end
}

This is working well for me. Vue2 projects use the vuels lsp, Vue3 projects use volar and tsserver with the @vue/typescript-plugin, and non-Vue ts projects do not import the vue plugin. Only callout is the global installation of the plugin's version has to match the version of volar installed via Mason.

@Jarmos-san
Copy link

Jarmos-san commented Apr 10, 2024

I'm not a major fan of polluting and bloating my hard disk and hence did not want to resort to installing neither typescript nor the plugin @vue/typescript-plugin globally! Yeah I know HDD space is cheap and all but its just my personal preference and that's how I like my development environment to be.

Any way, looks like the Vue projects requires both typescript and @vue/typescript-plugin installed (which btw should already be installed as dev dependencies). And as long as you follow the instructions in the README it should work flawlessly. For further reference here are the Neovim configurations I use for my Vue projects and the screenshots of one such project I'm currently working on.

image
image
image

I'm pretty sure there might be some caveats to the way I've configure Neovim (for now) but I couldn't find time to investigate further. Regardless, I guess as long as it works as I expect it to I will keep procrastinating! 😆

@k0mpreni
Copy link

k0mpreni commented Apr 18, 2024

Did it still fully work?
I still don't get full lsp, mostly missing the types on components and error for missing required components.
For the types it always takes the shims on a project.
I checked and it's working on vscode (I know it can mean anything) on this project and working with brand new vue project.
This is why I'm confused.

Here is my config: https://github.com/k0mpreni/nvim-lua/blob/7c130638d2f2d55f7dfd6bf3ebbbb154853481fb/after/plugin/lsp.lua#L18

Using mason:
typescript-language-server 4.3.3
vue-language-server 2.0.13

I tried the readme config and the setup from catgoose, without success.

edit: added plugin versions

@Jarmos-san
Copy link

@k0mpreni try adding these lines to your Neovim config:

lspconfig.volar.setup({
   filetypes = {'typescript', 'javascript', 'javascriptreact', 'typescriptreact', 'vue', 'json'},
   init_options = {
       vue = {
          hybridMode = false
       },
   }
})

It is based on the recommended configurations which you would find in the README (see my previous comment for source).

@k0mpreni
Copy link

Tried it as well @Jarmos-san , unfortunately same result, the type definition are from the shims and not from the component itself.

@RayGuo-ergou
Copy link
Contributor Author

image

Is this what are you referring to?

mostly missing the types on components and error for missing required components

One thing i can think of is: are the files included in tsconfig.json?

btw if you want to set hybridMode = false you should remove vue from tsserver, otherwise you will have 2 typescript server running at same time.

@k0mpreni
Copy link

Is this what are you referring to?

Exactly to those. It also seems that you have the shims as types no?
Component types are mostly useful for me as I want to have errors when I'm missing a required prop and if possible the props completion. Is it working for you @RayGuo-ergou ?

One thing i can think of is: are the files included in tsconfig.json?

Yes, it's in the tsconfig.json indeed. I also have it working in vscode with hybridMode on (had to put a specific tsdk as my project is not using typescript v5 yet).

@RayGuo-ergou
Copy link
Contributor Author

Component types are mostly useful for me as I want to have errors when I'm missing a required prop and if possible the props completion. Is it working for you

Yes they are working for me.
image

image

defineProps({
  msg: {
    type: String,
    required: true,
  },
})

had to put a specific tsdk as my project is not using typescript v5 yet

This might be the reason, the tsdk running on LSP does nothing to your project, as a LSP is just a stand along server maybe give typescript: "^5" a try.

@RayGuo-ergou
Copy link
Contributor Author

RayGuo-ergou commented Apr 18, 2024

image
image

btw have not used vscode for ages but it seems give the same shim type.

@k0mpreni
Copy link

Ok so it seems that it's just a ts version issue.
Strange however that in vscode when I explicitly say volar to use typescript v5 it's working, but not with the nvim config.
Best would be to update my project to ts v5 anyway.
Thanks!

@RayGuo-ergou
Copy link
Contributor Author

If you are using hybrid mode, the option tsdk in tsserver does not exit. If you want to declare the typescirpt path you should use tsserver.path.

see: https://github.com/typescript-language-server/typescript-language-server/blob/b224b878652438bcdd639137a6b1d1a6630129e4/docs/configuration.md?plain=1#L11

https://github.com/typescript-language-server/typescript-language-server/blob/b224b878652438bcdd639137a6b1d1a6630129e4/docs/configuration.md?plain=1#L41

@k0mpreni
Copy link

Ok so this is also doing the trick meanwhile I upgrade my project to v5. Can ditch vscode again thanks a lot!

For future reference:
If your project is not using a compatible version of TS with volar
Here is my config: https://github.com/k0mpreni/nvim-lua/blob/5948d7c8346f23863da68019929775b63321328c/after/plugin/lsp.lua#L17

If it's compatible, you don't need to override tsserver.path

@ulises-castro
Copy link

ulises-castro commented Jun 24, 2024

Context: This is a Vue 3 project without typescript.

This worked for me:

Notice I'm using some custom on_attach with Lspsaga.

-- Using Lspsaga If you like to ignore this, comment `on_attach = on_attach` 
local on_attach = function(client, bufnr)
  local opts = { noremap = true, silent = true, buffer = bufnr }
  keymap.set("n", "<leader>rn", "<cmd>Lspsaga rename<CR>", opts) -- smart rename
  vim.keymap.set("n", "K", "<cmd>Lspsaga hover_doc")
end


-- No need to set `hybridMode` to `true` as it's the default value
lspconfig.volar.setup({
  on_attach = on_attach,
  filetypes = { "typescript", "javascript", "javascriptreact", "typescriptreact", "vue" },
  init_options = {
    vue = {
      hybridMode = false,
    },
  },
})

@suinming
Copy link

suinming commented Sep 7, 2024

I am using vetur for vue2 project and volar for vue3 project. Using a simple function to detect the vue version.

config = function()
	local capabilities = require("mini.completion").completefunc_lsp()
	local lspconfig = require("lspconfig")
	local util = require("lspconfig.util")
	local mason_registry = require("mason-registry")
	local vue_language_server_path = mason_registry.get_package("vue-language-server"):get_install_path()
		.. "/node_modules/@vue/language-server"
	-- js, ts
	lspconfig.ts_ls.setup({
		init_options = {
			plugins = {
				{
					name = "@vue/typescript-plugin",
					location = vue_language_server_path,
					languages = { "vue" },
				},
			},
		},
		filetypes = { "typescript", "javascript", "javascriptreact", "typescriptreact", "vue" },
	})
	-- vue
	local function get_vue_version()
		local root_dir = util.find_git_ancestor(vim.fn.getcwd()) or vim.fn.getcwd()
		local package_json = root_dir .. "/package.json"

		if vim.fn.filereadable(package_json) == 1 then
			local package_data = vim.fn.json_decode(vim.fn.readfile(package_json))
			local vue_version = package_data["dependencies"] and package_data["dependencies"]["vue"]
				or package_data["devDependencies"] and package_data["devDependencies"]["vue"]

			if vue_version then
				-- Strip any non-numeric characters like ^ or ~ from the version string
				local cleaned_version = vim.fn.matchstr(vue_version, [[\v\d+]])
				local version = tonumber(cleaned_version)
				return version
			end
		end
		return nil
	end

	local vue_version = get_vue_version()

	if vue_version == 3 then
		-- use volar for vue 3
		lspconfig.volar.setup({
			capabilities = capabilities,
		})
	else
		-- use vetur (vuels) for vue 2
		lspconfig.vuels.setup({
			capabilities = capabilities,
			filetypes = { "vue" },
			root_dir = lspconfig.util.root_pattern("package.json", ".git"),
		})
	end
end,

@PixsaOJ
Copy link

PixsaOJ commented Sep 7, 2024

Volar is not able to run and have all capabilities no matter what. Use "typescript-tools" and @vue/typescript-plugin might take up resources, but its working.

@Ordeeper
Copy link

Ordeeper commented Dec 8, 2024

I'm trying to set up the Vue and TypeScript language servers in Neovim, but it’s not working as expected.

Configuration

Here’s my Lua configuration:

local mason_registry = require('mason-registry')
local vue_language_server_path = mason_registry.get_package('vue-language-server'):get_install_path() .. '/node_modules/@vue/language-server'

lspconfig.ts_ls.setup {
  init_options = {
    plugins = {
      {
        name = "@vue/typescript-plugin",
        location = vue_language_server_path,
        languages = { "vue" },
      },
    },
  },
  filetypes = { "typescript", "javascript", "javascriptreact", "typescriptreact", "vue" },
}
lspconfig.volar.setup {}
lspconfig.cssls.setup {}
lspconfig.phpactor.setup {}
lspconfig.yamlls.setup {}
lspconfig.html.setup {}
lspconfig.tailwindcss.setup {}

Active LSP Information

Command: :LspInfo

lspconfig: require("lspconfig.health").check()

LSP configs active in this session (globally) ~
- Configured servers: ts_ls, html, lua_ls, phpactor, cssls, volar, bashls, pylsp, tailwindcss, yamlls
- OK Deprecated servers: (none)

LSP configs active in this buffer (bufnr: 1) ~
- Language client log: ~/.local/state/nvim/lsp.log
- Detected filetype: `vue`
- 0 client(s) attached to this buffer
- Other clients that match the "vue" filetype:
- Config: volar
  filetypes:         vue
  cmd:               ~/.local/share/nvim/mason/bin/vue-language-server --stdio
  version:           `2.1.10`
  executable:        true
  autostart:         true
  root directory:    Not found.
- Config: tailwindcss
  filetypes:         aspnetcorerazor, astro, astro-markdown, blade, clojure, django-html, htmldjango, edge, eelixir, elixir, ejs, erb, eruby, gohtml, gohtmltmpl, haml, handlebars, hbs, html, htmlangular, html-eex, heex, jade, leaf, liquid, markdown, mdx, mustache, njk, nunjucks, php, razor, slim, twig, css, less, postcss, sass, scss, stylus, sugarss, javascript, javascriptreact, reason, rescript, typescript, typescriptreact, vue, svelte, templ
  cmd:               ~/.local/share/nvim/mason/bin/tailwindcss-language-server --stdio
  version:           `?` (Failed to get version) Tried:
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server --version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server -version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server --help`
  
  executable:        true
  autostart:         true
  root directory:    Not found.

Logs

Command: :LspStart ts_ls

Errors in LSP logs:

[START][2024-12-08 12:53:32] LSP logging initiated
[ERROR][2024-12-08 12:53:32] ...lsp/handlers.lua:623 "Notification handler 'textDocument/didOpen' failed with message: Cannot open document 'file:///home/arch-user/teste.vue' (languageId: vue)."
[ERROR][2024-12-08 12:53:32] ...lsp/handlers.lua:623 "Unexpected resource file:///home/arch-user/teste.vue"

@RayGuo-ergou
Copy link
Contributor Author

It's most likely due to root directory: Not found..

since you are using nvim-lspconfig by default, it will look up for package.json file to determine the root dir: https://github.com/neovim/nvim-lspconfig/blob/fc16fd4f9c5d72b45db0f45ee275db3a9a30481a/lua/lspconfig/configs/volar.lua#L19

@Ordeeper
Copy link

Ordeeper commented Dec 8, 2024

@RayGuo-ergou

Thank you for your reply! Unfortunately, it's still not working for me. Here’s the updated logs:

LspInfo

lspconfig: require("lspconfig.health").check()

LSP configs active in this session (globally) ~
- Configured servers: ts_ls, bashls, tailwindcss, lua_ls, html, yamlls, phpactor, cssls, volar, pylsp
- OK Deprecated servers: (none)

LSP configs active in this buffer (bufnr: 6) ~
- Language client log: ~/.local/state/nvim/lsp.log
- Detected filetype: `vue`
- 3 client(s) attached to this buffer
- Client: `ts_ls` (id: 1, bufnr: [6])
  root directory:    ~/Documents/works/senso/verohub-frontend/
  filetypes:         javascript, javascriptreact, javascript.jsx, typescript, typescriptreact, typescript.tsx
  cmd:               ~/.local/share/nvim/mason/bin/typescript-language-server --stdio
  version:           `4.3.3`
  executable:        true
  autostart:         true
- Client: `volar` (id: 2, bufnr: [6])
  root directory:    ~/Documents/works/senso/verohub-frontend/
  filetypes:         vue
  cmd:               ~/.local/share/nvim/mason/bin/vue-language-server --stdio
  version:           `2.1.10`
  executable:        true
  autostart:         true
- Client: `tailwindcss` (id: 3, bufnr: [6])
  root directory:    ~/Documents/works/senso/verohub-frontend/
  filetypes:         aspnetcorerazor, astro, astro-markdown, blade, clojure, django-html, htmldjango, edge, eelixir, elixir, ejs, erb, eruby, gohtml, gohtmltmpl, haml, handlebars, hbs, html, htmlangular, html-eex, heex, jade, leaf, liquid, markdown, mdx, mustache, njk, nunjucks, php, razor, slim, twig, css, less, postcss, sass, scss, stylus, sugarss, javascript, javascriptreact, reason, rescript, typescript, typescriptreact, vue, svelte, templ
  cmd:               ~/.local/share/nvim/mason/bin/tailwindcss-language-server --stdio
  version:           `?` (Failed to get version) Tried:
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server --version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server -version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server version`
  `/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server --help`

LspLog

[START][2024-12-08 20:32:41] LSP logging initiated
[ERROR][2024-12-08 20:32:41] ...lsp/handlers.lua:623	"Notification handler 'textDocument/didOpen' failed with message: Cannot open document 'file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue' (languageId: vue)."
[ERROR][2024-12-08 20:32:41] ...lsp/handlers.lua:623	"Unexpected resource file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue"
[WARN][2024-12-08 20:32:41] ...lsp/handlers.lua:135	"The language server tailwindcss triggers a registerCapability handler for workspace/didChangeWorkspaceFolders despite dynamicRegistration set to false. Report upstream, this warning is harmless"
[ERROR][2024-12-08 20:32:42] ...lsp/handlers.lua:623	"Unexpected resource file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue"
[ERROR][2024-12-08 20:32:43] ...lsp/handlers.lua:623	"Unexpected resource file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue"
[ERROR][2024-12-08 20:32:45] ...lsp/handlers.lua:623	"Unexpected resource file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue"

@RayGuo-ergou
Copy link
Contributor Author

The errors are likely come from ts_ls since it has (languageId: vue) you should see more detailed logs by setting the log level :h vim.lsp.log_levels.

One reason quickly come to my mind is your typescript version is below v5 ( typescript for LSPs not your project).

@Ordeeper
Copy link

Ordeeper commented Dec 9, 2024

@RayGuo-ergou

Thank you for the quick response! Here's the updated information after checking my setup:

      typescript-language-server ts_ls
      installed version 4.3.3                                                                    
      homepage          https://github.com/typescript-language-server/typescript-language-server 
      languages         TypeScript, JavaScript                                                   
      categories        LSP                                                                      
      executables       typescript-language-server                                               
      vue-language-server volar
      installed version 2.1.10                                  
      homepage          https://github.com/vuejs/language-tools 
      languages         Vue                                     
      categories        LSP                                     
      executables       vue-language-server                     

npm list -g --depth=0
(node:89568) ExperimentalWarning: CommonJS module /usr/lib/node_modules/npm/node_modules/debug/src/node.js is loading ES Module /usr/lib/node_modules/npm/node_modules/supports-color/index.js using require().
Support for loading ES Module in require() is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
/usr/lib
├── @vue/language-server@2.1.10
├── @vue/typescript-plugin@2.1.10
├── typescript-language-server@4.3.3
├── typescript@5.6.3

My logs with info level:

[START][2024-12-08 21:26:37] LSP logging initiated
[INFO][2024-12-08 21:26:37] .../vim/lsp/rpc.lua:731	"Starting RPC client"	{  cmd = { "/home/arch-user/.local/share/nvim/mason/bin/typescript-language-server", "--stdio" },  extra = {    cwd = "/home/arch-user/Documents/works/senso/verohub-frontend"  }}
[INFO][2024-12-08 21:26:37] .../vim/lsp/rpc.lua:731	"Starting RPC client"	{  cmd = { "/home/arch-user/.local/share/nvim/mason/bin/vue-language-server", "--stdio" },  extra = {    cwd = "/home/arch-user/Documents/works/senso/verohub-frontend"  }}
[INFO][2024-12-08 21:26:37] .../vim/lsp/rpc.lua:731	"Starting RPC client"	{  cmd = { "/home/arch-user/.local/share/nvim/mason/bin/tailwindcss-language-server", "--stdio" },  extra = {    cwd = "/home/arch-user/Documents/works/senso/verohub-frontend"  }}
[INFO][2024-12-08 21:26:37] ...lsp/handlers.lua:627	'Using Typescript version (workspace) 5.3.3 from path "/home/arch-user/Documents/works/senso/verohub-frontend/node_modules/typescript/lib/tsserver.js"'
[INFO][2024-12-08 21:26:37] ...m/lsp/client.lua:620	"LSP[ts_ls]"	"server_capabilities"	{  server_capabilities = {    callHierarchyProvider = true,    codeActionProvider = {      codeActionKinds = { "source.fixAll.ts", "source.removeUnused.ts", "source.addMissingImports.ts", "source.organizeImports.ts", "source.removeUnusedImports.ts", "source.sortImports.ts", "quickfix", "refactor" }    },    codeLensProvider = {      resolveProvider = true    },    completionProvider = {      resolveProvider = true,      triggerCharacters = { ".", '"', "'", "/", "@", "<" }    },    definitionProvider = true,    documentFormattingProvider = true,    documentHighlightProvider = true,    documentRangeFormattingProvider = true,    documentSymbolProvider = true,    executeCommandProvider = {      commands = { "_typescript.applyWorkspaceEdit", "_typescript.applyCodeAction", "_typescript.applyRefactoring", "_typescript.configurePlugin", "_typescript.organizeImports", "_typescript.applyRenameFile", "_typescript.goToSourceDefinition" }    },    foldingRangeProvider = true,    hoverProvider = true,    implementationProvider = true,    inlayHintProvider = true,    linkedEditingRangeProvider = false,    referencesProvider = true,    renameProvider = {      prepareProvider = true    },    selectionRangeProvider = true,    semanticTokensProvider = {      full = true,      legend = {        tokenModifiers = { "declaration", "static", "async", "readonly", "defaultLibrary", "local" },        tokenTypes = { "class", "enum", "interface", "namespace", "typeParameter", "type", "parameter", "variable", "enumMember", "property", "function", "member" }      },      range = true    },    signatureHelpProvider = {      retriggerCharacters = { ")" },      triggerCharacters = { "(", ",", "<" }    },    textDocumentSync = {      change = 2,      openClose = true,      save = {        includeText = false      },      willSave = false,      willSaveWaitUntil = false    },    typeDefinitionProvider = true,    workspace = {      fileOperations = {        willRename = {          filters = { {              pattern = {                glob = "**/*.{ts,js,jsx,tsx,mjs,mts,cjs,cts}",                matches = "file"              },              scheme = "file"            }, {              pattern = {                glob = "**",                matches = "folder"              },              scheme = "file"            } }        }      }    },    workspaceSymbolProvider = true  }}
[ERROR][2024-12-08 21:26:37] ...lsp/handlers.lua:623	"Notification handler 'textDocument/didOpen' failed with message: Cannot open document 'file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue' (languageId: vue)."
[ERROR][2024-12-08 21:26:37] ...lsp/handlers.lua:623	"Unexpected resource file:///home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue"
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"Setting up server…"
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"Listening for messages…"
[INFO][2024-12-08 21:26:38] ...m/lsp/client.lua:620	"LSP[tailwindcss]"	"server_capabilities"	{  server_capabilities = {    codeActionProvider = true,    colorProvider = true,    completionProvider = {      resolveProvider = true,      triggerCharacters = { '"', "'", "`", " ", ".", "(", "[", "]", "!", "/", "-", ":" }    },    documentLinkProvider = vim.empty_dict(),    hoverProvider = true,    textDocumentSync = {      change = 1,      openClose = true,      save = {        includeText = false      },      willSave = false,      willSaveWaitUntil = false    }  }}
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"Searching for Tailwind CSS projects in the workspace's folders."
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	'{"tailwind":{"version":"3.4.4","features":["layer:base","separator:root","content-list","jit","css-at-config-as-project","relative-content-paths","transpiled-configs"],"isDefaultVersion":true}}'
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"[Global] Creating projects: []"
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"[Global] Preparing projects..."
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"[Global] Initializing projects..."
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"[GLOBAL] No matching project for document {\n  fsPath: '/home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue',\n  normalPath: '/home/arch-user/Documents/works/senso/verohub-frontend/src/views/checkout/documents/DocumentsComponent.vue'\n}"
[INFO][2024-12-08 21:26:38] ...lsp/handlers.lua:627	"[Global] Initialized 0 projects"
[WARN][2024-12-08 21:26:38] ...lsp/handlers.lua:135	"The language server tailwindcss triggers a registerCapability handler for workspace/didChangeWorkspaceFolders despite dynamicRegistration set to false. Report upstream, this warning is harmless"
[INFO][2024-12-08 21:26:38] ...m/lsp/client.lua:620	"LSP[volar]"	"server_capabilities"	{  server_capabilities = {    codeActionProvider = {      resolveProvider = true    },    colorProvider = true,    completionProvider = {      resolveProvider = true,      triggerCharacters = { "*", "/", "-", ":", '"', ".", "<", "=", "@", ">", "+", "^", "(", ")", "#", "[", "]", "$", "{", "}" }    },    definitionProvider = true,    documentFormattingProvider = true,    documentHighlightProvider = true,    documentLinkProvider = vim.empty_dict(),    documentOnTypeFormattingProvider = {      firstTriggerCharacter = ";",      moreTriggerCharacter = { "}", "\n" }    },    documentRangeFormattingProvider = true,    documentSymbolProvider = true,    executeCommandProvider = {      commands = { "vue.parseSfc", "vue.detectNameCasing", "vue.convertTagsToKebabCase", "vue.convertTagsToPascalCase", "vue.convertPropsToKebabCase", "vue.convertPropsToCamelCase" }    },    experimental = {      autoInsertionProvider = {        configurationSections = { { "javascript.autoClosingTags", "typescript.autoClosingTags", "html.autoClosingTags" }, { "html.autoCreateQuotes" }, { "html.autoClosingTags" }, { "vue.autoInsert.dotValue" }, { "vue.autoInsert.bracketSpacing" } },        triggerCharacters = { ">", "=", "/", "\\w", "}" }      },      documentDropEditsProvider = true    },    foldingRangeProvider = true,    hoverProvider = true,    inlayHintProvider = vim.empty_dict(),    linkedEditingRangeProvider = true,    referencesProvider = true,    renameProvider = {      prepareProvider = true    },    selectionRangeProvider = true,    textDocumentSync = {      change = 2,      openClose = true,      save = {        includeText = false      },      willSave = false,      willSaveWaitUntil = false    },    workspace = {      workspaceFolders = {        changeNotifications = true,        supported = true      }    }  }}

@RayGuo-ergou
Copy link
Contributor Author

Hi @yuzhen1024 I think you had the similar issue, are you able to help here? How did you figured out a solution?

@yuzhen1024
Copy link

yuzhen1024 commented Dec 12, 2024

@RayGuo-ergou
Basically did nothing. #4912 (comment)

@Ordeeper
Copy link

Unsuccessful :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests