一、 单个ts文件的编译
-
tsc app.ts;
- 将app.ts文件编译为js文件,在网页中引入即可
tsc app.ts --watch // 监视
- 将app.ts文件编译为js文件,更改ts文件后将持续监视文件
-
tsc
- tsconfig.json是ts编译器的配置文件,ts编译器可以根据它的信息来对代码进行编译
二、 多个ts文件的编译
- 将所有需要编译的ts文件放置在src目录下
- src的父级目录下需要进行tsconfig.json文件的配置
2-1 目录结构
2-2 配置tsconfig.json文件
{
"compilerOptions": {
"module": "ES2015",
"target": "es5",
"strict": true,
"outDir": "./dist"
},
"include": ["./src/**/*"]
}
2-2-1 补充: 配置选项
-
include: 用来指定哪些ts文件需要被编译【包含哪个目录的文件】
-
路径: ** 表示任意目录
-
*: 表示任意文件
-
-
exclude:不需要被编译的文件目录
- 默认值:[“node_modules”,“bower_components”,“jspm_packages”]
-
{ "include": [ "./src/**/*" ], "exclude": [ "./src/hello/**/*" ] }
-
- compilerOptions :
- target : 用来指定ts被编译为js的版本
- outDir 用来指定编译后文件所在的目录
- module :指定要使用的模块化的规范
Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'es2022', 'esnext', 'node16', 'nodenext'.
- compilerOptions :
-
extends:
-
定义被继承的配置文件
-
"extends": "./configs/base"
-
-
files:
-
指定被编译文件的列表,只有需要编译的文件少时才会用到
-
"files": [ "core.ts" ]
-
-
outDir: 用来指定编译后文件所在的目录
"outDir": "/dist"
-
outFile: 将代码合并为一个文件
- “outFile”: “./dist/app.js”
- 设置outFile后,所有的全局作用域中的代码会合并到同一个文件中
-
"allowJs":false
- 是否对JS文件进行编译
-
"checkJs": false
- 是否检查js代码是否符合语法规范,默认是false
-
"removeComments": true // 是否移除注释
-
"noEmit": true // 不生成编译后的文件
-
"noEmitError": true // 当有错误时不生成编译后的文件
-
"alwaysStrict": false // 用来设置编译后的文件是否使用严格模式,默认为false
2-3 执行
tsc -w
js文件自动输出在dist文件夹下
在index.html引入即可