美文网首页
浅谈如何用 VS Code 舒服地编码

浅谈如何用 VS Code 舒服地编码

作者: 风之化身呀 | 来源:发表于2018-11-24 14:35 被阅读60次

前言

现在写前端代码基本都 ES6 了,更前沿的都开始使用 TS 了。本文的目标是:配置项目和编辑器,使写代码更舒服。更舒服一般体现在3点:

  • 保存后实时报错(lint)
  • 保存后自动格式化(prettier)
  • 代码提交时自动lint且格式化(husky),确保团队代码风格统一

支持 ES6

  • 转ES5
    .babelrc
// react 项目
{
    "presets": [
        "env",
        "react"
    ],
    "plugins": [ "babel-plugin-transform-runtime","transform-object-rest-spread"] // 转换 rest 和 spread operator  runtime转异步函数
}
// react-native 项目
{
  "presets": ["module:metro-react-native-babel-preset"]
}
  • Eslint
    安装 eslint 和安装vs code 的 eslint 插件,书写 .eslintrc 文件
    插件的目的是实时提示错误,否则只能通过命令行编译后才知道错误
{
  "plugins": ["react", "prettier"],
  "globals": {
    "__DEV__": true,
    "__dirname": false,
    "__fbBatchedBridgeConfig": false,
    "cancelAnimationFrame": false,
    "clearImmediate": true,
    "clearInterval": false,
    "clearTimeout": false,
    "console": false,
    "document": false,
    "escape": false,
    "exports": false,
    "fetch": false,
    "global": false,
    "jest": false,
    "Map": true,
    "module": false,
    "navigator": false,
    "process": false,
    "Promise": true,
    "requestAnimationFrame": true,
    "require": false,
    "Set": true,
    "setImmediate": true,
    "setInterval": false,
    "setTimeout": false,
    "window": false,
    "XMLHttpRequest": false,
    "alert": true,
    "pit": false,
    "ReactElement": true
  },

  "parser": "babel-eslint",

  "env": {
    "es6": true
  },

  "rules": {
    "no-undef": "error",
    "react/jsx-boolean-value": 0,
    "react/jsx-curly-spacing": 1,
    "react/jsx-indent-props": [1, 2],
    "react/jsx-key": 1,
    "react/jsx-max-props-per-line": 0,
    "react/jsx-no-duplicate-props": 1,
    "react/jsx-no-undef": 2,
    "react/jsx-pascal-case": 1,
    "react/jsx-uses-react": 1,
    "react/jsx-uses-vars": 1,
    "react/no-danger": 1,
    "react/no-deprecated": 1,
    "react/no-did-mount-set-state": 0,
    "react/no-did-update-set-state": 1,
    "react/no-direct-mutation-state": 1,
    "react/no-is-mounted": 1,
    "react/no-multi-comp": [1, {"ignoreStateless": true}],
    "react/no-set-state": 0,
    "react/no-unknown-property": 1,
    "react/prefer-es6-class": 1,
    "react/react-in-jsx-scope": 1,
    "react/self-closing-comp": 1,
    "react/sort-comp": 1,
    "react/jsx-wrap-multilines": 1,
    "react/prop-types": [2, { "ignore": [ "children", "navigation" ]}],
    "jsx-quotes": 1,
    "prettier/prettier": "error"
  }
}

  • Prettier
    安装 Prettier 和安装vs code 的 Prettier 插件,书写.prettierrc。
    插件的目的是实时提示错误,否则只能通过命令行编译后才知道错误
{
    "printWidth": 80,
    "tabWidth": 2,
    "useTabs": false,
    "semi": true,
    "singleQuote": true,
    "trailingComma": "none",
    "bracketSpacing": true,
    "jsxBracketSameLine": false,
    "arrowParens": "avoid",
    "rangeStart": 0,
    "parser": "babylon",
    "requirePragma": false,
    "insertPragma": false,
    "proseWrap": "preserve"
}
  • Eslint 结合 Prettier
    安装 eslint-plugin-prettier ,这会让eslint调用prettier来格式化代码
    若是 react 项目,还需安装 eslint-plugin-react。
    最后开启编辑器设置:
"prettier.eslintIntegration": true,
"eslint.autoFixOnSave": true,
"editor.formatOnSave": true,
  • Prettier 结合 Husky
    1、安装 husky 和 lint-staged
    2、修改 package.json 配置,设置 precommit 和 lint-staged
{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.{js,jsx}": ["eslint --fix", "git add"]
  }
}

支持 TS

tslint.json

{
  "defaultSeverity": "error",
  "extends": [
    "tslint-react",
    "tslint-config-prettier"
  ],
  "jsRules": {},
  "rules": {},
  "rulesDirectory": []
}

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES2015",
    /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",
    /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "react",
    /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,
    /* Enable all strict type-checking options. */
    "noImplicitAny": true,
    /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,
    /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    "noImplicitThis": true,
    /* Raise error on 'this' expressions with an implied 'any' type. */
    "alwaysStrict": true,
    /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,
    /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

需要注意的是:
1、在 tslint 中想让代码被 prettier 格式化有个前提,就是 tslint 必须全部编译通过。若一个文件报了 tslint 错误,那么该文件是不会被 prettier 格式化的。这个也是 不如 eslint 可以自动格式化的地方。
2、使用 TS 时,.prettierrc 中的 parser 要设为:'typescript',否则不能使用诸如 enum 之类的关键字(使用了代码不会报错,但 prettier 格式化工具会报错,你这个文件也就无法被 prettier 格式化)


image.png

参考

相关文章

网友评论

      本文标题:浅谈如何用 VS Code 舒服地编码

      本文链接:https://www.haomeiwen.com/subject/uhbhqqtx.html