TypeScript & React(下)

目录

TypeScript & React

TS开发环境的搭建

tsconfig.json

webpack.config.js

babel.config.js

.eslintrc.js


TypeScript & React

TS开发环境的搭建

  • 软件版本:TypeScript:3.9.5;React:16.13.1 Node:8.17.0
  • 环境搭建:正确搭建一个通用的TypeScript开发环境

差异:

  • tsconfig->babel->eslint

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./",
    "target": "esnext",
    "allowJs": true,
    "noEmit": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "experimentalDecorators": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "jsx": "react",
    "sourceMap": true,
    "pretty": true,
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    },
  },  
  "typeRoots": [
    "node_modules/@types",
    "src/types"
  ],
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.spec.ts"
  ],
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const devPort = parseInt(process.env.port, 10) || 8065;
module.exports = (env) => {
  const publicPath = '';
  const buildPath = './build';
  const config = {
    mode: env.prod ? 'production' : 'development',
    entry: {
      app: path.join(__dirname, './src/index.tsx'),
    },
    devServer: {
      historyApiFallback: true,
      contentBase: path.join(__dirname, buildPath),
      port: devPort,
      hot: true,
      disableHostCheck: true,
    },
    output: {
      path: path.join(__dirname, buildPath),
      pathinfo: true,
      filename: env.prod || env.test ? '[name].[hash].js' : '[name].js',
      publicPath: `${publicPath}/`,
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
    },
    module: {
      rules: [
        {
          test: /(\.ts|\.tsx)$/,
          exclude: /(node_modules)/,
          use: [
            {
              // 新增支持ts编译
              loader: 'babel-loader',
            },
          ],
        },
        {
          test: /\.css$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
              options: {
                importLoaders: 1,
              },
            },
            {
              loader: 'postcss-loader',
            },
          ],
        },
      ],
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.ENV': env.dev,
      }),
      new webpack.LoaderOptionsPlugin({ options: {} }),
      new HtmlWebpackPlugin({
        title: 'React & TypeScript',
        template: path.join(__dirname, './src/view/index.html'),
        inject: true,
        hash: false,
        filename: 'index.html',
        publicPath: '',
      }),
    ],
    devtool: 'source-map',
    watch: true,
  };
  return config;
};

babel.config.js

module.exports = (api) => {
  api.cache(true);
  const plugins = [
    require('@babel/plugin-transform-runtime'),
    [require('@babel/plugin-proposal-decorators'), { legacy: true }],
    [require('@babel/plugin-proposal-class-properties'), { loose: true }],
    require('@babel/plugin-proposal-export-default-from'),
    // require("react-hot-loader/babel"),
  ];
  const presets = [
    [
      require('@babel/preset-env'),
      {
        modules: false,
        useBuiltIns: 'usage',
        corejs: { version: 3, proposals: true },
      },
    ],
    [require('@babel/preset-react')],
    // 插件将ts、tsx转译为js
    [require('@babel/preset-typescript')],
  ];
  return {
    plugins,
    presets,
  };
};

.eslintrc.js

const path = require('path');
module.exports = {
  root: true,
  // 新增ts的编译
  parser: '@typescript-eslint/parser',
  extends: [
    'airbnb-typescript',
    'airbnb/hooks',
    // 新增tslint推荐
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
  // 新增@typescript-eslint配置项
  plugins: ['@typescript-eslint', 'jsx-a11y', 'import', 'react-hooks'],
  parserOptions: {
    ecmaVersion: 2019,
    sourceType: 'module',
    // 关联ts配置文境
    project: './tsconfig.json',
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: {
          resolve: {
            alias: {
              '@': path.resolve(__dirname, './src'),
            },
            extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
          },
        },
      },
    },
  },
  env: {
    browser: true,
  },
  globals: {
    window: true,
    ENV: true,
  },
  rules: {
    indent: ['error', 2],
    quotes: ['error', 'single'],
    semi: ['error', 'always'],
    'no-console': 1,
    'arrow-parens': 0,
    'no-shadow': 'off',
    'react/jsx-filename-extension': 'off',
    'react/jsx-props-no-spreading': 0,
    // 自定义规则
    '@typescript-eslint/consistent-type-definitions': ['error', 'interface'],
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 0,
    'import/extensions': [
      'error',
      'ignorePackages',
      {
        ts: 'never',
        tsx: 'never',
        js: 'never',
        jsx: 'never',
        json: 'never',
      },
    ],
    'import/no-unresolved': [2, { commonjs: true, amd: true }],
  },
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值