Skip to content

20.使用新语言来开发项目-使用TypeScript语言 #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
webVueBlog opened this issue Sep 22, 2022 · 0 comments
Open

20.使用新语言来开发项目-使用TypeScript语言 #20

webVueBlog opened this issue Sep 22, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

TypeScript 是 JavaScript 的一个超集,主要提供了类型检查系统和对 ES6 语法的支持,但不支持新的 API。 目前没有任何环境支持运行原生的 TypeScript 代码,必须通过构建把它转换成 JavaScript 代码后才能运行。

{
  "compilerOptions": {
    "module": "commonjs", // 编译出的代码采用的模块规范
    "target": "es5", // 编译出的代码采用 ES 的哪个版本
    "sourceMap": true // 输出 Source Map 方便调试
  },
  "exclude": [ // 不编译这些目录里的文件
    "node_modules"
  ]
}
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": false,
    "jsx": "preserve",
    // 从 tslib 导入外部帮助库: 比如__extends,__rest等
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "noImplicitThis": false,
    // 允许从没有设置默认导出的模块中默认导入
    "allowSyntheticDefaultImports": true,
    // "resolveJsonModule": true,
    //编译时去除掉注释
    "removeComments": true,
    // 是否包含可以用于 debug 的 sourceMap
    "sourceMap": true,
    // 输出目录
    "outDir": "jsOutPut",
    // 解析非相对模块名的基准目录
    "baseUrl": ".",
    "types": [
      "node",
      "jest",
      "webpack-env"
    ],
    // 指定特殊模块的路径
    "paths": {
      "@/*": [
        "src/*"
      ],
      "components": [
        "src/components"
      ]
    },
    // 编译过程中需要引入的库文件的列表
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
  ],
  "exclude": [
    "node_modules"
  ]
}

减少代码冗余

{
  "compilerOptions": {
    "importHelpers": true
  }
}

集成 Webpack

通过 Loader 把 TypeScript 转换成 JavaScript。

Webpack 在寻找模块对应的文件时需要尝试 ts 后缀。

推荐速度更快的 awesome-typescript-loader

const path = require('path');

module.exports = {
  // 执行入口文件
  entry: './main',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
  },
  resolve: {
    // 先尝试 ts 后缀的 TypeScript 源码文件
    extensions: ['.ts', '.js']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  },
  devtool: 'source-map',// 输出 Source Map 方便在浏览器里调试 TypeScript 代码
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant