📜  带有 babel 的 typescript - TypeScript (1)

📅  最后修改于: 2023-12-03 14:54:02.537000             🧑  作者: Mango

带有 babel 的 typescript

简介

TypeScript 是 JavaScript 的超集,可以在编写代码时提供类型检查和更好的开发体验。但是,TypeScript 在浏览器环境中的支持不如 Node.js 和现代前端框架那么好。

babel 是一个 JavaScript 编译器,提供了用于转换 JavaScript 代码的插件机制。开发者可以通过 babel 插件将 TypeScript 转换成浏览器环境下的 JavaScript 代码。

在开发过程中,使用 babel 转换 TypeScript 可以提供更好的浏览器兼容性和更好的开发体验。

安装

安装 babel 和 TypeScript 以及相关插件:

npm install --save-dev @babel/core @babel/preset-typescript @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime
npm install --save-dev typescript
使用

在项目的根目录下添加一个 .babelrc 文件,用于配置 babel:

{
  "presets": [
    "@babel/preset-typescript",
    ["@babel/preset-env", {
      "targets": {
        "chrome": "58",
        "ie": "11"
      }
    }]
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-runtime"
  ]
}

在项目的根目录下添加一个 tsconfig.json 文件,用于配置 TypeScript:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "ES2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "strict": true,
    "noImplicitAny": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "dist"
  }
}

在项目中编写 TypeScript 代码,并使用 babel 转换成浏览器可用的 JavaScript 代码:

class Greeter {
  private greeting: string;

  constructor(message: string) {
    this.greeting = message;
  }

  public greet() {
    return "Hello, " + this.greeting;
  }
}

const greeter = new Greeter("world");
document.body.textContent = greeter.greet();

使用 babel 转换 TypeScript 代码:

npx babel index.ts --out-file dist/index.js

现在,我们已经可以在浏览器中运行转换后的代码了。

结论

带有 babel 的 TypeScript 可以提供更好的浏览器兼容性和更好的开发体验。在使用前,请务必了解 TypeScript 和 babel 的相关知识。