How can I setup eslint to format on save?

I am trying to setup eslint to fix all errors on the current buffer when I save it.

Here is my lsp config:

local lspconfig = require('lspconfig')

local on_attach = function(client, bufnr)
    -- enable format on save
    require "lsp-format".on_attach(client)

    local opts = {
        noremap = true,
        silent = true
    vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', '<leader>.', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', '[d', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts)
    vim.api.nvim_buf_set_keymap(bufnr, 'n', ']d', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts)

local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities)

lspconfig.eslint.setup {
    on_attach = on_attach,
    capabilities = capabilities,
    settings = {
        codeActionOnSave = {
            enable = true,
            mode = "all"

I thought maybe setting “codeActionsOnSave=true” would make this happen, but that doesn’t seem to be the case. What am I missing?

vim.api.nvim_create_autocmd("BufWritePost", {
    callback = function()

Hey, I tried this solution but it does nothing.

Looks like the eslint language server uses code actions for this. The documentation has this snippet:

autocmd BufWritePre *.tsx,*.ts,*.jsx,*.js EslintFixAll

Have you tried that?

That eslint lsp doesn’t expose formatting like that. But it exposes a command to format. So you can create an autocmd:

vim.api.nvim_create_autocmd('BufWritePre', {
  pattern = { '*.tsx', '*.ts', '*.jsx', '*.js' },
  command = 'silent! EslintFixAll',
  group = vim.api.nvim_create_augroup('MyAutocmdsJavaScripFormatting', {}),
1 Like