node.js在vscode的配置

发布于:2025-06-21 ⋅ 阅读:(20) ⋅ 点赞:(0)

概要

node.js在webstrom编辑器中可以完美使用代码提示、错误提示等功能,但是在vscode中编辑node.js有一堆问题,为了使vscode有和nodejs一样的功能,我尝试了各种配置,现分享出来。

1. 使用和webstrom一样的快捷键

对于熟悉JetBrains产品的coder来说,当你切换到vscode工具时,会发现快捷及其难用,就算我记住了,长时间不用vscode又会忘记该命令,实在受不了我就寻找一劳永逸的方案。

结果发现了vscode有款插件,可以直接让你在vscode使用JetBrains快捷键命令: IntelliJ IDEA Keybindings
在这里插入图片描述

2. 让vscode的主题变成webstrom

没啥好讲的,还是借助vscode插件: Webstorm IntelliJ Darcula Theme,上图:

在这里插入图片描述

3. 如何在 Node.js 环境下写代码

在vscode写node.js代码时,会出现没有错误提示的问题,所以写代码就是就很不爽,不能及时发现潜在bug,这个问题困扰我半天,经过一顿搜索发现解决方案:

3.1 使用 ESLint配置规则

  • 要检查哪些文件?
  • 使用什么 JavaScript 语法版本?
  • 哪些全局变量是合法的?
  • 开启/关闭哪些代码规范规则?

使用 ESLint配置规则需要先安装 ESLint

npm install eslint --save-dev

安装完后编写配置规则

  • 需要在项目的根目录下新建一个eslint.config.js
  • eslint.config.js 是 ESLint v9 及以上版本推荐使用的新格式配置文件 (推荐使用)

规则如下:

//eslint.config.js文件
const eslintPlugin = require('@eslint/js');

module.exports = [
  eslintPlugin.configs.recommended,
  {
    files: ['**/*.js'],
    languageOptions: {
      ecmaVersion: 2017,
      sourceType: 'commonjs',
      globals: {
        require: 'readonly',
        module: 'readonly',
        __dirname: 'readonly',
        console: 'readonly', // 这里告诉 ESLint console 是已定义的全局变量
        process: 'readonly', // 允许使用 process 全局变量
      },
    },
    rules: {
      strict: 'off', // 关闭 strict 规则
      'no-undef': 'error',
      'no-unused-vars': 'error',
      eqeqeq: 'error',
      'no-console': 'off', // 关闭 no-console 规则,允许使用 console
      'no-debugger': 'error',
      'no-var': 'error',
      'prefer-const': 'error',
    },
    ignores: ['eslint.config.cjs'], // 忽略自己
  },
];

解释:

这个配置的作用是:

  • 检查所有 .js 文件的语法和风格
  • 使用 Node.js 环境(CommonJS、ES2017)
  • 强制使用现代 JavaScript 语法
  • 合理配置全局变量,避免误报
  • 提高代码规范性(比如禁用 var、禁止未使用变量)
  • 忽略自身配置文件,避免循环报错

3.2 配置.vscode/settings.json

这是 VS Code 编辑器的本地设置文件 ,用于控制编辑器的行为,比如:

  • 是否在保存时自动修复 ESLint 错误
  • 是否启用 ESLint 插件
  • 使用哪个 JavaScript/TypeScript 版本高亮
  • 是否启用智能提示等
`.vscode/settings.json文件`
{
  "javascript.validate.enable": false, // 禁用内置 JS 验证
  "typescript.validate.enable": true, // 禁用 TS 验证
  "editor.showUnused": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "prettier.singleQuote": true,
  "prettier.trailingComma": "all",
  "prettier.printWidth": 120,

  // ✅ 启用 ESLint 插件对 JS 文件检查
  "eslint.validate": ["javascript"],

  // ✅ 启用 ESLint 自动修复
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },

  // ✅ 自动识别项目根目录
  "eslint.workingDirectories": [{ "mode": "auto" }],

  // ✅ 强制插件使用项目本地 ESLint(9.x)
  "eslint.useESLintClass": true,

  // 显示标尺(刻度线)
  "editor.rulers": [80, 120]
}

这段配置让 VS Code 更加适合使用 ESLint + Prettier 的开发环境,能实现:

  • 保存时自动格式化和修复
  • 使用项目自己的 ESLint(而不是全局的)
  • 高亮未使用变量
  • 配置 Prettier 的代码风格

4. Prettier安装

自动格式化代码插件:Prettier - Code formatter
在这里插入图片描述

5. 其它问题解决

在这里插入图片描述
在.vscode/settings.json文件中加上:

{
  "javascript.validate.enable": false, // 禁用内置 JS 验证
  "typescript.validate.enable": true, // 禁用 TS 验证
}

即可解决。