webpack高级应用篇(七):在 webpack 工程化环境中集成 TypeScript

如何在在 webpack 工程化环境中集成 TypeScript

基础配置

安装我们的 ts 和对应的 loader

npm i typescript -S
# 或
yarn add typescript
npm i ts-loader -D

在项目根目录下添加一个ts的配置文件——tsconfig.json,我们可以用ts自带的工具来自动化生成它。

npx tsc --init

我们发现生成了一个tsconfig.json,里面注释掉了绝大多数配置。

在这里插入图片描述

现在,根据我们想要的效果来打开对应的配置。

{
    
    
  "compilerOptions": {
    
    
    "outDir": "./dist/",
    "noImplicitAny": true,
    "sourceMap": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node"
  }
}

src/index.ts

const num: number = 20;
console.log('num', num);

webapck.config.js

const path = require('path');

module.exports = {
    
    
  entry: './src/index.ts',
  output: {
    
    
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  devtool: 'inline-source-map',
  resolve: {
    
    
    extensions: ['.tsx', '.ts', '.js'],
  },
  module: {
    
    
    rules: [{
    
    
      test: /\.ts$/,
      use: 'ts-loader',
      exclude: /node_modules/,
    },
    ],
  },
};

执行 webpack可以看到 ts 已经被编译为 js

在这里插入图片描述


使用第三方类库

在从 npm 上安装第三方库时,一定要记得同时安装这个库的类型声明文件(typing definition)。

我们可以从 TypeSearch 中找到并安装这些第三方库的类型声明文件(https://www.typescriptlang.org/dt/search?search=) 。

举个例子,如果想安装 lodash 类型声明文件,我们可以运行下面的命令:

npm i lodash
npm i @types/lodash --save-dev

在 TypeScript 使用 ESLint

在前面我们已经研究过 webpack 结合 ESLint webpack高级应用篇(三):ESLint

未配置过 ESLint

如果要使用 eslint,使用初始化命令的时候,记得选择 使用了 typesctipt

npx eslint --init
# 往下选择的时候选择使用了typesctipt

在这里插入图片描述


已配置过 ESLint,但没有配置 ts

如果已经配置了 eslint,但没有配置 ts 的配置,那么我们需要先安装对应的 plugin

npm i -D @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest

注意如果需要用到 react 的话,记得也要安装

npm i -D eslint-plugin-react@latest

vue或者其他常用框架同样如此,一般都会有专门的plugin。

.esilntrc

module.exports = {
    
    
  env: {
    
    
    browser: true,
    es2021: true,
    es6: true,
  },
  extends: [
    'airbnb-base',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    
    
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint'],
  rules: {
    
    
    // ...
  },
};

执行 npx eslint ./src 试一下!

大功告成!

Guess you like

Origin blog.csdn.net/qq_41887214/article/details/121870684