TypeScript安装与编译
安装
bash
npm i typescript -g
编译
bash
tsc index.ts 编译ts->js
tsc index.ts --watch # 监听index.ts变化,自动编译成js
tsc --watch # 监听所在目录ts文件变化,自动编译成js
Vscode+TypeScript
生成配置文件
bash
tsc --init
javascript
{
"compilerOptions": {
/* Basic Options */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. 指定ECMAScript的目标版本*/
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. 指定模块代码的生成方式*/
// "lib": [], /* Specify library files to be included in the compilation. 指定编译的时候用来包含的编译文件*/
// "allowJs": true, /* Allow javascript files to be compiled. 允许编译JS文件*/
// "checkJs": true, /* Report errors in .js files. 在JS中包括错误*/
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. 指定JSX代码的生成方式 是保留还是react-native或者react*/
// "declaration": true, /* Generates corresponding '.d.ts' file.生成相应的类型声明文件 */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. 为每个类型声明文件生成相应的sourcemap*/
// "sourceMap": true, /* Generates corresponding '.map' file. 生成对应的map文件 */
// "outFile": "./", /* Concatenate and emit output to single file. 合并并且把编译后的内容输出 到一个文件里*/
// "outDir": "./", /* Redirect output structure to the directory.按原始结构输出到目标目录 */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. 指定输入文件的根目录,用--outDir来控制输出的目录结构*/
// "composite": true, /* Enable project compilation 启用项目编译*/
// "removeComments": true, /* Do not emit comments to output. 移除注释*/
// "noEmit": true, /* Do not emit outputs. 不要输出*/
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. 当目标是ES5或ES3的时候提供对for-of、扩展运算符和解构赋值中对于迭代器的完整支持*/
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule').r把每一个文件转译成一个单独的模块 */
/* Strict Type-Checking Options */
//"strict": true, /* Enable all strict type-checking options. 启用完全的严格类型检查 */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. 不能使用隐式的any类型*/
// "strictNullChecks": true, /* Enable strict null checks. 启用严格的NULL检查*/
// "strictFunctionTypes": true, /* Enable strict checking of function types. 启用严格的函数类型检查*/
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions.启用函数上严格的bind call 和apply方法 */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. 启用类上初始化属性检查*/
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type.在默认的any中调用 this表达式报错 */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. 在严格模式下解析并且向每个源文件中发射use strict*/
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. 有未使用到的本地变量时报错 */
// "noUnusedParameters": true, /* Report errors on unused parameters. 有未使用到的参数时报错*/
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. 当不是所有的代码路径都有返回值的时候报错*/
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. 在switch表达式中没有替代的case会报错 */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). 指定模块的解析策略 node classic*/
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. 在解析非绝对路径模块名的时候的基准路径*/
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. 一些路径的集合*/
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. 根目录的列表,在运行时用来合并内容*/
// "typeRoots": [], /* List of folders to include type definitions from. 用来包含类型声明的文件夹列表*/
// "types": [], /* Type declaration files to be included in compilation.在编译的时候被包含的类型声明 */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking.当没有默认导出的时候允许默认导入,这个在代码执行的时候没有作用,只是在类型检查的时候生效 */
//"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.*/
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks.不要symlinks解析的真正路径 */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. 指定ts文件位置*/
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. 指定 map文件存放的位置 */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. 源文件和sourcemap 文件在同一文件中,而不是把map文件放在一个单独的文件里*/
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. 源文件和sourcemap 文件在同一文件中*/
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. 启动装饰器*/
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
}
}
vscode运行
执行ts代码,安装ts-node,右键run code
bash
npm i ts-node -g
通过rollup构建工具
webpack、rollup、esbuild(在生产环境不友好)
初始化项目
bash
npm init -y
npm i rollup typescript rollup-plugin-typescript2 @rollup/plugin-node-resolve -D
安装tsc
bash
npm i typescript -g
tsc --init
tsconfig.json
diff
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
+ "module": "ESNext", /* Specify what module code is generated. */
/* JavaScript Support */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
/* Completeness */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
rollup.config.js
配置rollup
js
// 默认 rollup 打包时会查找当前目录下 rollup.config.js 这个文件
// 采用 es 模块来编写配置文件(在 package.json中增加 "type": "module")
import ts from 'rollup-plugin-typescript2'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import path from 'path'
import { fileURLToPath } from 'url'
// es module格式下不支持直接使用__dirname,需要手动获取
// 当前文件的绝对路径 file://xxxx/xx/xx
const __filename = fileURLToPath(import.meta.url) // 当前文件的绝对路径
const __dirname = path.dirname(__filename) // 当前文件所在的文件夹目录 绝对路径
export default {
input: './src/index.ts', // 项目入口
output: {
file: path.resolve(__dirname, 'dist/bundle.js'),
format: 'iife', // (function(){})() 打包格式
},
plugins: [
nodeResolve({ extensions: ['.js', '.ts'] }), // 第三方包入口 入口文件可以是js或ts
ts({
tsconfig: path.resolve(__dirname, 'tsconfig.json')
})
]
}
添加脚本 package.json
json
{
"name": "ts-learn",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "dev": "rollup -c -w" # -c 使用配置文件 -w 监听文件变化
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"rollup": "^4.5.0",
"rollup-plugin-typescript2": "^0.36.0",
"typescript": "^5.2.2"
},
+ "type": "module"
}
添加入口文件,src/index.ts
ts
let a: string = 'hello'
console.log(a);
运行项目
bash
npm run dev
生成dist/bundle.js
js
(function () {
'use strict';
let a = 'hello';
console.log(a);
})();
创建html
dist/index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./bundle.js"></script>
</body>
</html>
支持soucemap
rollup.config.js
diff
// 默认 rollup 打包时会查找当前目录下 rollup.config.js 这个文件
// 采用 es 模块来编写配置文件(在 package.json中增加 "type": "module")
import ts from 'rollup-plugin-typescript2'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import path from 'path'
import { fileURLToPath } from 'url'
// es module格式下不支持直接使用__dirname,需要手动获取
// 当前文件的绝对路径 file://xxxx/xx/xx
const __filename = fileURLToPath(import.meta.url) // 当前文件的绝对路径
const __dirname = path.dirname(__filename) // 当前文件所在的文件夹目录 绝对路径
export default {
input: './src/index.ts', // 项目入口
output: {
file: path.resolve(__dirname, 'dist/bundle.js'),
format: 'iife', // (function(){})() 打包格式
+ sourcemap: true, // 打包后调试源代码
},
plugins: [
nodeResolve({ extensions: ['.js', '.ts'] }), // 第三方包入口 入口文件可以是js或ts
ts({
tsconfig: path.resolve(__dirname, 'tsconfig.json')
})
]
}
tsconfig.json
diff
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
"module": "ESNext", /* Specify what module code is generated. */
/* Emit */
+ "sourceMap": true, /* Create source map files for emitted JavaScript files. */
/* JavaScript Support */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
/* Completeness */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
src/index.ts
ts
let a: string = 'hello'
debugger
console.log(a);