ts配置

发布时间 2023-10-17 08:54:52作者: 长安城下翩翩少年

我们将使用 babel 去编译 TypeScript,babel 在编译 TypeScript 代码是直接去掉 TypeScript 的类型,然后当成普通的 javascript 代码使用各种插件进行编译,tsc 并没有介入编译过程,因此 tsconfig.json 中很多选项例如 target 和 module 是没有用的,可以让 VSCode 等编辑器正确提示错误
在项目中使用ts
yarn add typescript -D
// 新建 tsconfig.json 文件,进行ts 配置

通过babel来编译ts文件
yarn add babel-loader @babel/core @babel/preset-typescript -D
在babel.config.js 中配置
module.exports = function (api) {
api.cache(true);
const presets = ['@babel/preset-typescript'];
const plugins = [];
return { presets, plugins, };
};

在webpack 中配置 babel-loader
{
test: /.(tsx?|js)$/,
loader: 'babel-loader',
// 开启缓存
options: { cacheDirectory: true },
exclude: /node_modules/,
}