在Typescript项目中,使用ESLint和Prettier,以及解决保存代码后ESLint配置冲突问题

首先,检查项目中根目录.eslintrc.js文件,该文件中定义了ESLint的基础配置,找到其中的rules

例如:

 const prettierConfig = require('./.prettierrc.js')

module.exports = {
  root: true,
  parserOptions: { ecmaVersion: 2021 },
  overrides: [
    rules: {
      'prettier/prettier': ['error', prettierConfig],
      'jsdoc/newline-after-description': 1,
      '@typescript-eslint/no-this-alias': 'error',
      '@typescript-eslint/member-ordering': 'off',
      'no-irregular-whitespace': 'error',
      'no-multiple-empty-lines': 'error',
      'no-sparse-arrays': 'error',
      'prefer-object-spread': 'error',
      'prefer-template': 'error',
      'prefer-const': 'off',
      'max-len': 'off',
    },
  ],
}

由此可以看到,配置项在./.prettierrc.js,开始执行你的配置吧~~~~

找到./.prettierrc.js

请注意下面代码,是解决代码冲突的重要场景

module.exports = {
  singleQuote: true,
  useTabs: false,
  printWidth: 50,
  tabWidth: 2,
  semi: false,
  htmlWhitespaceSensitivity: 'strict',
  arrowParens: 'avoid',
  bracketSpacing: true,
  wrapAttributes: true,
  sortAttributes: true,
  proseWrap: 'preserve',
  trailingComma: 'none',
  endOfLine: 'lf'
};

然后检查你的项目中是否有这个文件,

请注意下面代码中的注释部分,是解决代码冲突的重要场景

.vscode\settings.json

{
  "typescript.tsdk": "./node_modules/typescript/lib",
  "editor.formatOnSave": false,  // 重点关注这个,这个会影响到你的保存代码是否自动修改代码哦~~
  "editor.codeActionsOnSave": {
    // For ESLint
    "source.fixAll.eslint": false, // 重点关注这个,这个会影响到你的保存代码是否自动修改代码哦~~
    // For Stylelint
    "source.fixAll.stylelint": false // 重点关注这个,这个会影响到你的保存代码是否自动修改代码哦~~
  },
  "[markdown]": {
    "editor.formatOnSave": false
  },
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[json]": {
    "editor.formatOnSave": false
  },
  "[jsonc]": {
    "editor.formatOnSave": false
  },
  "files.watcherExclude": {
    "**/.git/*/**": true,
    "**/node_modules/*/**": true,
    "**/dist/*/**": true,
    "**/coverage/*/**": true
  },
  "files.associations": {
    "*.json": "jsonc",
    ".prettierrc": "jsonc",
    ".stylelintrc": "jsonc"
  },
  // Angular schematics 插件: https://marketplace.visualstudio.com/items?itemName=cyrilletuzi.angular-schematics
  "ngschematics.schematics": [
    "ng-alain"
  ]
}

另外,你的VS code 编辑器,也有一个 settings.json文件,在 File - Preferences - Settings 中可以找到这个文件,里边的有些配置项,也会和项目中的配置造成冲突,请保证和代码配置修改为一致

例如,下面的配置就比较乱,需要改为和项目配置一样的~~

{
    "editor.minimap.enabled": false,
    "[html]": {
        "editor.defaultFormatter": "vscode.html-language-features"
    },
    "window.zoomLevel": 1,
    "[json]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "files.autoSave": "off",
    // 老版本的eslint
    // "editor.codeActionsOnSave": {
    //     "source.fixAll.eslint": false
    // },
    // "eslint.validate": [
    //     "javascript",
    //     "javascriptreact",
    //     "vue-html",
    //     "html",
    //     {
    //         "language": "vue",
    //         "autoFix": false
    //     },
    //     {
    //         "language": "typescript",
    //         "autoFix": false
    //     },
    //     {
    //         "language": "typescriptreact",
    //         "autoFix": false
    //     }
    // ],
    "eslint.run": "onSave",
    // "eslint.autoFixOnSave": false,
    "files.associations": {
        "/path to file/*.extension": "language"
    },
    // tab 大小为2个空格
    "editor.tabSize": 2,
    // 100 列后换行
    "editor.wordWrapColumn": 100,
    // 开启 vscode 文件路径导航
    "breadcrumbs.enabled": true,
    // prettier 设置语句末尾不加分号
    "prettier.semi": false,
    // prettier 设置强制单引号
    "prettier.singleQuote": true,
    // 选择 vue 文件中 template 的格式化工具
    "vetur.format.defaultFormatter.html": "prettyhtml",
    // 显示 markdown 中英文切换时产生的特殊字符
    "editor.renderControlCharacters": true,
    // eslint 检测文件类型
    "[vue]": {
        "editor.defaultFormatter": "octref.vetur"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "workbench.colorTheme": "Default Light+",
    // vetur 的自定义设置
    // "vetur.format.defaultFormatterOptions": {
    //     "prettier": {
    //         "singleQuote": true,
    //         "semi": false,
    //         "tabWidth": 2
    //     }
    // },
    "vetur.format.defaultFormatterOptions": {
        "prettyhtml": {
            // 单行超过100个长度的时候开始换行
            "printWidth": 50,
            "tabWidth": 2,
            "useTabs": false,
            "singleQuote": false,
            "wrapAttributes": true,
            "sortAttributes": true
        }
    },
    // 禁用vetur的JS格式化,交给eslint处理
    "vetur.format.defaultFormatter.js": "none",
    "window.autoDetectColorScheme": true,
    "problems.showCurrentInStatus": true,
    "eslint.alwaysShowStatus": true,
    "VSCodeCounter.showInStatusBar": true,
    "zenMode.hideStatusBar": false,
    "http.proxy": "http://ics.foxconn.com/dpbg.pac",
    "eslint.codeAction.showDocumentation": {
        "enable": true
    },
    //autoFixedOnSave 设置已废弃,采用如下新的设置
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": false
    },
    "eslint.format.enable": true,
    "editor.formatOnSave": false,
    //autoFix默认开启,只需输入字符串数组即可
    "eslint.validate": [
        "javascript",
        "vue",
        "html",
        "javascriptreact",
        "vue-html",
        "html",
        "typescript",
        "typescriptreact"
    ]
}

改完就OK 了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先你需要安装webpack5、react、typescripteslint以及相关的loader和插件。你可以通过以下命令安装它们: ``` npm install webpack webpack-cli webpack-dev-server react react-dom @types/react @types/react-dom typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks prettier -D ``` 接下来,你需要创建一个webpack配置文件,可以命名为`webpack.config.js`,在该文件配置webpack相关内容: ```javascript const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.tsx', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|tsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ], }, }, { loader: 'ts-loader', }, ], }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), ], devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, }, mode: 'development', }; ``` 在上面的配置,我们指定了入口文件为`src/index.tsx`,打包后的输出文件为`dist/bundle.js`。我们还通过resolve属性指定了文件的拓展名,这样在引入文件时就不用指定拓展名了。 在module属性,我们定义了不同类型文件的loader,例如对于`.tsx`和`.ts`文件,我们使用了`babel-loader`和`ts-loader`,对于`.js`和`.jsx`文件,我们只使用了`babel-loader`。此外,我们还使用了`style-loader`和`css-loader`处理`.css`文件。 在plugins属性,我们使用了`HtmlWebpackPlugin`插件,用于生成HTML文件。在devServer属性,我们指定了开发服务器的端口和从哪个文件夹提供内容。 最后,我们使用了`inline-source-map`作为开发模式下的source-map,将模式设置为`development`。 接下来,你需要创建一个`.babelrc`文件,用于配置babel: ```json { "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"] } ``` 然后,你需要创建一个`.eslintrc.json`文件,用于配置eslint: ```json { "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": ["airbnb", "plugin:@typescript-eslint/recommended", "prettier"], "rules": { "prettier/prettier": ["error"], "react/jsx-filename-extension": [1, { "extensions": [".tsx"] }], "import/extensions": ["error", "never", { "svg": "always" }] }, "settings": { "import/resolver": { "node": { "extensions": [".js", ".jsx", ".ts", ".tsx"] } } } } ``` 在上面的配置,我们使用了`@typescript-eslint/parser`解析Typescript代码,并使用了`@typescript-eslint/eslint-plugin`插件提供的规则。我们还继承了`eslint-config-airbnb`和`eslint-config-prettier`,并使用了一些自定义的规则。 最后,你需要在`package.json`添加一些scripts,用于启动开发服务器和打包代码: ```json { "scripts": { "start": "webpack serve --mode development", "build": "webpack --mode production" } } ``` 现在你就可以使用`npm start`命令启动开发服务器,使用`npm run build`命令打包代码了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值