安装

  1. npm i -g typescript

编译

1、命令行编译

创建文件 1.ts
  1. let a = 10;
  2. //编译为:var a = 10;

编译
  1. # 默认编译为 1.js
  2. ts 1.ts
  3. # 编译为指定文件 bundle.js
  4. tsc 1.ts --outfile bundle.js
  5. # 监听
  6. tsc 1.ts --watch
  7. # 模块生成规范
  8. tsc 1.ts --module commonjs

2、code runner 用node环境来执行ts

生成配置文件 tsconfig.json
  1. tsc --init

执行编译
  1. tsc # 编译
  2. tsc --watch # 编译并监听

vscode 运行
  • Terminal->Run Task-> tsc:build 编译
  • Terminal->Run Task-> tsc:watch 编译并监听

右键 run code 运行

需要先安装 ts-node 插件

  1. cnpm i ts-node -g

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. /* 基本参数 */
  4. /*生成es版本:'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT' */
  5. "target": "es5",
  6. /*模块生成规范:'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext' */
  7. "module": "ESNEXT",
  8. /*指定编译的时候用来包含的编译文件*/
  9. // "lib": ["dom", "ESNext"],
  10. "jsx": "react", /* 指定jsx代码用于的开发环境: 'preserve', 'react-native', or 'react'. */
  11. "sourceMap": true, /* 指定编译时是否生成.map文件 */
  12. "downlevelIteration": true, /*允许迭代器进行迭代,比如使用for...of循环遍历具有iterator接口的数据*/
  13. "declaration": true, /* 指定编译时是否生成声明文件 */
  14. "outDir": "./dist", /* 指定编译输出文件夹,值为一个文件夹路径字符串,输出的文件都将放置在这个文件夹 */
  15. /* 检查相关参数 */
  16. "strict": true, /* 是否启动所有类型检查*/
  17. // "strictFunctionTypes": true, /*在 Ts 中,参数类型是双向协变的,也就是说既是协变又是逆变的,而这并不安全。strictFunctionTypes 就是修复这个问题的。是否开启函数参数类型严格模式*/
  18. // "strictNullChecks": true, /* 是否严格执行空检查 */
  19. "noImplicitAny": true, /* 如果我们没有为一些值设置明确的类型,编译器会默认认为这个值为any,如果noImplicitAny的值为true的话。则没有明确的类型会报错。默认值为false */
  20. /* 模块解析相关参数 */
  21. "moduleResolution": "node", /* 选择模块解析策略,有'node''classic'两种类型' */
  22. "esModuleInterop": true, /* 通过为导入内容创建命名空间,实现CommonJSES模块之间的互操作性 */
  23. /* 设置解析非相对模块名称的基本目录,相对模块不会受baseUrl的影响 */
  24. "baseUrl": "./",
  25. /* 设置模块名称到基于baseUrl的路径映射 */
  26. "paths": {
  27. // "*": ["./types/*"],
  28. "@/*": ["./src/*"], //把@映射为src目录
  29. },
  30. "allowSyntheticDefaultImports": true, /* 指定允许从没有默认导出的模块中默认导入 */
  31. /* Experimental Options */
  32. "experimentalDecorators": true, /*让ts支持装饰器*/
  33. /* Advanced Options */
  34. "skipLibCheck": true, /* Skip type checking of declaration files. */
  35. "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
  36. },
  37. // 要编译哪些文件夹下的文件
  38. "include": [
  39. "./src/**/*", //* 匹配任意字符,不包括路径分隔符;** 匹配任意字符,包括路径分隔符
  40. // "./types/**/*",
  41. ]
  42. }
  1. {
  2. "compilerOptions": {
  3. /* Visit https://aka.ms/tsconfig.json to read more about this file */
  4. /* Basic Options */
  5. // "incremental": true, /* Enable incremental compilation */
  6. "target": "es5", /* 指定编译生成的es版本: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
  7. "module": "commonjs", /* 模块生成标准: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
  8. "lib": ["dom", "ESNext"], /*指定要包含在编译中的库文件*/
  9. "allowJs": true, /* 是否允许编译js文件,默认是false */
  10. "checkJs": true, /* 是否检查和报告js文件中的错误,默认是false */
  11. "jsx": "preserve", /* 指定jsx代码用于的开发环境: 'preserve', 'react-native', or 'react'. */
  12. /* 是否在编译的时候生成相应的".d.ts"声明文件。
  13. 如果设为true,编译每个ts文件之后会生成一个js文件和一个声明文件。但是declarationallowJs不能同时设为true */
  14. "declaration": true,
  15. "declarationMap": true, /* 是否为 声明文件.d.ts 生成map文件 */
  16. "sourceMap": true, /* 指定编译时是否生成.map文件 */
  17. /* 指定将输出文件合并为一个文件,它的值为一个文件路径名。
  18. 比如设置为"./dist/main.js",则输出的文件为一个main.js文件。
  19. 但是要注意,只有设置module的值为amdsystem模块时才支持这个配置。 */
  20. "outFile": "./",
  21. "outDir": "./", /* 指定输出文件夹,值为一个文件夹路径字符串,输出的文件都将放置在这个文件夹 */
  22. /* 用来指定编译文件的根目录,编译器会在根目录查找入口文件,
  23. 如果编译器发现以rootDir的值作为根目录查找入口文件并不会把所有文件加载进去的话会报错,但是不会停止编译。 */
  24. "rootDir": "./",
  25. "composite": true, /* 是否编译构建引用项目 */
  26. "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
  27. "removeComments": true, /* 是否将编译后的文件中的注释删掉,默认为false */
  28. "noEmit": true, /* 不生成编译文件,这个一般比较少用 */
  29. "importHelpers": true, /* 是否引入tslib里的辅助工具函数,默认为false */
  30. "downlevelIteration": true, /* target'ES5' or 'ES3'时,为'for-of', spread, and destructuring'中的迭代器提供完全支持 */
  31. "isolatedModules": true, /* 是否将每个文件作为单独的模块,默认为true,它不可以和declaration同时设定 */
  32. /* Strict Type-Checking Options */
  33. "strict": true, /* 是否启动所有类型检查,如果设为true则会同时开启下面这几个严格类型检查,默认为false */
  34. /* 如果我们没有为一些值设置明确的类型,编译器会默认认为这个值为any
  35. 如果noImplicitAny的值为true的话。则没有明确的类型会报错。默认值为false */
  36. "noImplicitAny": true,
  37. /* true时,nullundefined值不能赋给 非这两种类型 的值,别的类型也不能赋给他们,
  38. 除了any类型。还有个例外就是undefined可以赋值给void类型 */
  39. "strictNullChecks": true,
  40. /* 是否使用函数参数双向协变检查
  41. Ts 中,参数类型是双向协变的,也就是说既是协变又是逆变的,而这并不安全。strictFunctionTypes 就是修复这个问题的。 */
  42. "strictFunctionTypes": true,
  43. "strictBindCallApply": true, /* bindcallapply绑定的方法的参数的检测 是否开启严格检测 */
  44. /* 是否开启检查 类的非undefined属性 是否已经在构造函数里初始化,
  45. 如果要开启这项,需要同时开启strictNullChecks,默认为false */
  46. "strictPropertyInitialization": true,
  47. "noImplicitThis": true, /* 开启后,当this表达式的值为any类型的时候,生成一个错误 */
  48. "alwaysStrict": true, /* 指定始终以严格模式检查每个模块,并且在编译之后的js文件中加入"use strict"字符串,用来告诉浏览器该js为严格模式 */
  49. /* Additional Checks */
  50. "noUnusedLocals": true, /* 检查 是否有定义了但是没有使用的变量,默认值为false */
  51. "noUnusedParameters": true, /* 检查 是否有在函数体中没有使用的参数,默认为false */
  52. "noImplicitReturns": true, /* 检查 函数是否有返回值,设为true后,如果函数没有返回值则会提示,默认为false */
  53. "noFallthroughCasesInSwitch": true, /* 检查 switch中是否有case没有使用break跳出switch,默认为false */
  54. "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
  55. /* Module Resolution Options */
  56. "moduleResolution": "node", /* 选择模块解析策略,有'node''classic'两种类型' */
  57. "baseUrl": "./", /* 设置解析非相对模块名称的基本目录,相对模块不会受baseUrl的影响 */
  58. "paths": {}, /* 设置模块名称到基于baseUrl的路径映射 */
  59. "rootDirs": [], /* 指定一个路径列表,在构建时编译器会将这个路径列表中的路径的内容都放到一个文件夹中 */
  60. "typeRoots": [], /* 指定声明文件或文件夹的路径列表,如果指定了此项,则只有在这里列出的声明文件才会被加载 */
  61. "types": [], /* 指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载进来 */
  62. "allowSyntheticDefaultImports": true, /* 指定允许从没有默认导出的模块中默认导入 */
  63. "esModuleInterop": true, /* 通过为导入内容创建命名空间,实现CommonJSES模块之间的互操作性 */
  64. "preserveSymlinks": true, /* 不把符号链接解析为其真实路径,具体可以了解下webpacknodejssymlink相关知识 */
  65. "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
  66. /* Source Map Options */
  67. "sourceRoot": "", /* 指定调试器应该找到TypeScript文件而不是源文件位置,这个值会被写进.map文件里 */
  68. "mapRoot": "", /* 指定调试器找到映射文件而非生成文件的位置,指定map文件的根路径,该选项会影响.map文件中的sources属性 */
  69. "inlineSourceMap": true, /* 是否将map文件的内容和js文件编译在同一个js文件中,如果设为true,则map的内容会以//# sourceMappingURL=然后拼接base64字符串的形式插入在js文件底部 */
  70. "inlineSources": true, /* 用于指定是否进一步将.ts文件的内容也包含到输入文件中 */
  71. /* Experimental Options */
  72. "experimentalDecorators": true, /* 指定是否启用实验性的装饰器特性 */
  73. /* 指定是否为装饰器提供元数据支持,关于元数据,也是ES6的新标准,可以通过Reflect提供的静态方法获取元数据,
  74. 如果需要使用Reflect的一些方法,需要引入ES2015.Reflect这个库 */
  75. "emitDecoratorMetadata": true,
  76. /* Advanced Options */
  77. "skipLibCheck": true, /* Skip type checking of declaration files. */
  78. "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  79. },
  80. // 配置一个数组列表,里面包含指定文件的相对或绝对路径,编译器在编译的时候只会编译包含在files中列出的文件,
  81. // 如果不指定,则取决于有没有设置include选项,
  82. // 如果没有include选项,则默认会编译根目录以及所有子目录中的文件。
  83. // 这里列出的路径必须是指定文件,而不是某个文件夹,而且不能使用 * ? **/ 等通配符
  84. "files": [],
  85. // 指定要编译的路径列表,但是和files的区别在于,这里的路径可以是文件夹,也可以是文件,
  86. // 可以使用相对和绝对路径,而且可以使用通配符,比如"./src"即表示要编译src文件夹下的所有文件以及子文件夹的文件
  87. "include": [
  88. "src/**/*", //* 匹配任意字符,不包括路径分隔符;** 匹配任意字符,包括路径分隔符
  89. "typings/**/*"
  90. ],
  91. // 表示要排除的、不编译的文件,它也可以指定一个列表,规则和include一样,可以是文件或文件夹,可以是相对路径或绝对路径,可以使用通配符
  92. "exclude": [],
  93. // 通过指定一个其他的tsconfig.json文件路径,来继承这个配置文件里的配置,继承来的文件的配置会覆盖当前文件定义的配置。
  94. // TS3.2版本开始,支持继承一个来自Node.js包的tsconfig.json配置文件
  95. "extends": "",
  96. // 如果设为true,在我们编辑了项目中的文件保存的时候,编辑器会根据tsconfig.json中的配置重新生成文件,不过这个要编辑器支持
  97. "compileOnSave": true,
  98. "references": [], // 一个对象数组,指定要引用的项目
  99. }

3、构建工具来处理ts

  • webpack
  • rollup

解析ts的方式有两种

  • ts插件来解析
  • 通过babel来解析

rollup

rollup 一般情况下会采用 rollup-plugin-typescript2。

安装依赖
  1. cnpm i -D
  2. rollup
  3. typescript
  4. rollup-plugin-typescript2
  5. @rollup/plugin-node-resolve
  6. rollup-plugin-serve
  7. cross-env

tsconfig.json
  1. {
  2. "compilerOptions": {
  3. /* 基本参数 */
  4. /*生成es版本:'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT' */
  5. "target": "es5",
  6. /*模块生成规范:'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext' */
  7. "module": "ESNEXT",
  8. "sourceMap": true, /* 指定编译时是否生成.map文件 */
  9. "downlevelIteration": true, /*允许迭代器进行迭代,比如使用for...of循环遍历具有iterator接口的数据*/
  10. /* 检查相关参数 */
  11. "strict": true, /* 是否启动所有类型检查*/
  12. /*在 Ts 中,参数类型是双向协变的,也就是说既是协变又是逆变的,而这并不安全。strictFunctionTypes 就是修复这个问题的。是否开启函数参数类型严格模式*/
  13. // "strictFunctionTypes": true,
  14. /* 模块解析相关参数 */
  15. "moduleResolution": "node", /* 选择模块解析策略,有'node''classic'两种类型' */
  16. "esModuleInterop": true, /* 通过为导入内容创建命名空间,实现CommonJSES模块之间的互操作性 */
  17. /* Experimental Options */
  18. "experimentalDecorators": true, /*让ts支持装饰器*/
  19. /* Advanced Options */
  20. "skipLibCheck": true, /* Skip type checking of declaration files. */
  21. "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */
  22. }
  23. }

package.json
  1. "scripts": {
  2. "dev": "cross-env my_env=development rollup --config --watch",
  3. "build": "cross-env my_env=production rollup --config"
  4. },

rollup.config.js
  1. import ts from 'rollup-plugin-typescript2';
  2. import {nodeResolve} from '@rollup/plugin-node-resolve';
  3. import serve from 'rollup-plugin-serve';
  4. import path from 'path';
  5. // 环境变量
  6. const myEnv = process.env.my_env;
  7. const isDev = myEnv === 'development'; //是否开发环境
  8. const myCmd = process.env.npm_lifecycle_event; //scripts脚本命令
  9. let rollupConfig = {
  10. input: './src/index.ts', // 打包输入文件
  11. output: { // 打包输出
  12. file: path.resolve(__dirname, 'dist/bundle.js'),
  13. sourcemap: true,
  14. format: 'iife', //输出格式:amd/es/iife/umd/cjs/system
  15. name: 'calculator', //输出格式为 iife或umd的时候必须提供,将会作为一个全局变量保持在window下。
  16. },
  17. // 插件
  18. plugins: [
  19. nodeResolve({
  20. extensions: ['.js', '.ts'],
  21. }),
  22. ts({
  23. tsconfig: path.resolve(__dirname, 'tsconfig.json'), //指定ts使用哪个配置文件
  24. }),
  25. ],
  26. };
  27. if (isDev){
  28. rollupConfig.plugins = rollupConfig.plugins.concat([
  29. serve({
  30. // open: true, //自动打开
  31. port: 8080,
  32. contentBase: '', //根目录
  33. openPage: '/public/index.html', //默认打开根目录下的哪个目录
  34. }),
  35. ]);
  36. } else {
  37. rollupConfig.plugins = rollupConfig.plugins.concat([]);
  38. }
  39. export default rollupConfig;

public/index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script src="/dist/bundle.js"></script>
  11. </body>
  12. </html>