tsconfig - typescript配置

  1. // tsconfig.json
  2. {
  3. "compilerOptions": {
  4. "moduleResolution": "Node", // 模块解析规则
  5. "target": "es5", // 指定ECMAScript目标版本
  6. "jsx": "preserve",
  7. "module":"es2015", // 模块系统代码
  8. "lib": ["es2015", "es2016", "es2017", "dom"], // 指定api使用的版本,例如Map或Math
  9. "declaration": true, // 生成相应的 .d.ts文件
  10. "outDir": "dist/lib", // .js的文件输出路径
  11. "declarationDir": "dist/types", // .d.ts文件输出路径
  12. "strict": true // 严格类型检查,
  13. "allowSyntheticDefaultImports": true // 可使用默认导入语法 import React from "react"
  14. },
  15. "include": [
  16. "src"
  17. ]
  18. }

:::tips strict开启后会自动启用以下规则

  1. strictNullChecks
  2. strictBindCallApply
  3. strictPropertyInitialization
  4. strictFunctionTypes
  5. noImplicitThis(强制显示注解函数中this的类型,不强制类或对象的函数注解this) :::

:::tips module详解

  1. 如果使用systemJS模块加载器,把module设为systemjs
  2. 如果使用兼容ES2015的模块打包工具,例如webpack或rollup,设为es2015或更高版本
  3. 如果是发布一个库,应该使用umd
  4. 如果使用兼容ES2015的模块打包工具,而且代码中用到了动态导入,设为esnext
  5. 如果使用commonJS打包工具打包模块,例如Browserify,设为commonjs
  6. 如果打算使用RequireJS或其他AMD模块加载器加载代码,把module设为umd :::

RollupJs - 模块化构建

  1. // rollup.config.ts
  2. import typescript from 'rollup-plugin-typescript2'
  3. import pkg from './package.json'
  4. import { terser } from "rollup-plugin-terser"
  5. export default {
  6. input: 'src/index.ts',
  7. plugins: [
  8. typescript({ useTsconfigDeclarationDir: true }) // to find tsconfig.json
  9. ],
  10. output: [
  11. {
  12. file: pkg.main,
  13. format: 'umd', // cmj or iife
  14. name: 'easyFetch', // bundle name
  15. plugins: [terser()] // minify bundle
  16. },
  17. { file: pkg.umd, format: "umd", name: 'easyFetch' },
  18. { file: pkg.module, format: 'es' },
  19. ]
  20. };

esLint - 代码风格

  1. // .eslintrc.js
  2. module.exports = {
  3. 'env': {
  4. 'browser': true,
  5. 'es2021': true,
  6. 'node': true
  7. },
  8. 'extends': [
  9. 'eslint:recommended',
  10. 'plugin:@typescript-eslint/recommended'
  11. ],
  12. 'parser': '@typescript-eslint/parser',
  13. 'parserOptions': {
  14. 'ecmaVersion': 12,
  15. 'sourceType': 'module'
  16. },
  17. 'plugins': [
  18. '@typescript-eslint'
  19. ],
  20. 'rules': {
  21. 'indent': [ // 缩进使用tab
  22. 'error',
  23. 'tab'
  24. ],
  25. 'linebreak-style': [ // 换行风格
  26. 'error',
  27. 'unix'
  28. ],
  29. 'quotes': [ // 单引号
  30. 'error',
  31. 'single'
  32. ],
  33. 'semi': [ // 不使用分号
  34. 'error',
  35. 'never'
  36. ],
  37. "@typescript-eslint/no-explicit-any": 0, // 禁用any提示
  38. "@typescript-eslint/explicit-module-boundary-types": 0,
  39. "@typescript-eslint/no-extra-semi": 0
  40. }
  41. }

prettier - 格式化代码

  1. // .prettierrc.js
  2. module.exports = {
  3. // 箭头函数只有一个参数的时候可以忽略括号
  4. arrowParens: 'avoid',
  5. tabWidth: 2,
  6. useTabs: true,
  7. parser: 'typescript',
  8. // 行宽
  9. printWidth: 120,
  10. // 分号
  11. semi: false,
  12. // 使用单引号
  13. singleQuote: true,
  14. // 后置逗号,多行对象、数组在最后一行不增加逗号
  15. trailingComma: 'none'
  16. }