You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Neovim(LazyVim)中JavaScript/TypeScript缩进问题

解决LazyVim中JavaScript/TypeScript缩进失效问题

问题分析

核心问题是Python缩进功能正常,但JavaScript/TypeScript仅支持一级缩进,结合配置和环境来看,问题源于Treesitter配置冲突、缩进规则未针对JS/TS生效,以及重复的LSP配置干扰。

分步解决方案

1. 修复Treesitter配置冲突

你的lua/plugins/example.lua存在两处问题:开头的if true then return {} end会直接返回空表,导致所有自定义插件配置失效;同时存在重复的Treesitter配置,覆盖了解析器规则。

修改lua/plugins/example.lua为:

return {
  -- 复用LazyVim官方的TypeScript配置,无需重复编写
  { import = "lazyvim.plugins.extras.lang.typescript" },

  -- 扩展Treesitter解析器,确保JS/TS语法被支持
  {
    "nvim-treesitter/nvim-treesitter",
    opts = function(_, opts)
      vim.list_extend(opts.ensure_installed, {
        "javascript",
        "typescript",
        "tsx",
      })
    end,
  },

  -- 安装必要的格式化工具(可选,用于JS/TS代码格式化)
  {
    "williamboman/mason.nvim",
    opts = {
      ensure_installed = {
        "stylua",
        "shellcheck",
        "shfmt",
        "flake8",
        "prettier",
      },
    },
  },
}

2. 针对JS/TS配置专属缩进规则

在lua/config/options.lua中添加文件类型自动命令,确保缩进规则对JS/TS生效:

vim.g.mapleader = " "

vim.scriptencoding = "utf-8"
vim.opt.encoding = "utf-8"
vim.opt.fileencoding = "utf-8"

vim.opt.number = true

vim.opt.title = true
vim.opt.autoindent = true
vim.opt.smartindent = true
vim.opt.hlsearch = true
vim.opt.backup = false
vim.opt.showcmd = true
vim.opt.cmdheight = 0
vim.opt.laststatus = 0
vim.opt.expandtab = true
vim.opt.scrolloff = 10
vim.opt.inccommand = "split"
vim.opt.ignorecase = true
vim.opt.smarttab = true
vim.opt.breakindent = true
vim.opt.shiftwidth = 2
vim.opt.tabstop = 2
vim.opt.wrap = false
vim.opt.backspace = { "start", "eol", "indent" }
vim.opt.path:append({ "**" })
vim.opt.wildignore:append({ "*/node_modules/*" })
vim.opt.splitbelow = true
vim.opt.splitright = true
vim.opt.splitkeep = "cursor"

-- Add asterisks in block comments
vim.opt.formatoptions:append({ "r" })

-- 针对JS/TS设置专属缩进规则
vim.api.nvim_create_autocmd("FileType", {
  pattern = {"javascript", "typescript", "javascriptreact", "typescriptreact"},
  callback = function()
    vim.opt_local.cindent = true
    vim.opt_local.smartindent = true
    vim.opt_local.shiftwidth = 2
    vim.opt_local.tabstop = 2
    vim.opt_local.expandtab = true
  end,
})

3. 验证Treesitter状态

打开任意JS文件,运行:checkhealth treesitter,确保javascript和typescript解析器状态为OK。如果显示未安装,执行:TSInstall javascript typescript完成安装。

4. 测试缩进功能

创建新JS文件,输入以下代码测试多级缩进:

const testIndent = () => {
  if (true) {
    console.log("二级缩进正常");
    for (let i = 0; i < 5; i++) {
      console.log("三级缩进正常");
    }
  }
};

按Enter换行后,光标应自动跳转到对应缩进层级,无需手动按Tab。

5. 排查插件冲突(可选)

如果问题仍存在,暂时禁用mini-indentscope插件,在lua/config/lazy.lua中注释掉对应的导入:

-- { import = "lazyvim.plugins.extras.ui.mini-indentscope" },

重启Neovim后测试缩进,确认是否为该插件导致的冲突。

内容的提问来源于stack exchange,提问作者Harikesh Ranjan Sinha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:18:09