纯JS项目改造为TypeScript踩坑

  1. 添加 typescript 依赖和 tsconfig.json
$ yarn tsc --init

其中 yarn tsc --init 使用本地刚安装的 typescript 初始化了一个 tsconfig.json 含有很多默认配置的文件

修改 tsconfig.json 为以下内容 (可自行配置)

{
  "compilerOptions": {
    "outDir": "./dist/",
    "rootDir": "./src/",
    "sourceMap": true,
    "strict": true,
    "noImplicitAny": false,
    "module": "es6",
    "target": "es5"
  }
}

查看TypeScript官方配置选项

  1. 将所有 js 文件修改为 ts 文件
$ cd src
$ find . -name "*.js" | sed 's/.js//' | xargs -n1 -I {} mv {}.js {}.ts
  1. 修复出错的 ts 文件

执行以下命令来检查有多少个文件需要修改

yarn tsc
  1. 让 webpack 支持编译 typescript
    我们接下来我们需要让 webpack 认识 ts 文件并且以 typescript 自己的编译器进行转化, 安装 ts-loader
$ yarn add -D ts-loader

然后添加 webpack.config.js 文件中对 ts 文件的解析 (自行追加)

webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.ts?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ '.ts', '.js', '.json' ]
  },
};

参考资料

posted @ 2021-11-03 14:41  王猪猴  阅读(416)  评论(0编辑  收藏  举报