Skip to main content

intro

学习目标

ts配置

环境准备

  1. 安装vscode

  2. 安装node环境

  3. 安装ts

bash
1
2
npm install -g typescript

官网在安装ts时,多了--save-dev选项,该选项是干吗用的呢?

优化编译

1.解决ts和js冲突问题

初始化配置

bash
1
2
npx tsc --init

2.如何实现在修改代码时,自动完成编译

bash
1
2
tsc --watch

3.发出错误,如果遇到错误就停止编译

bash
1
2
tsc -noEmitOnError

tsc参数之单横杠与双横杠

在将ts编译成js后,在浏览器中运行,结果报如下错误:

bash
1
2
Uncaught ReferenceError: exports is not defined

这个错误是因为CommonJS模块在浏览器环境中无法直接运行,浏览器不认识exports,require,module等CommonJS特有的变量.

解决方案:

修改tsconfig.json中的模块系统

json
1
2
3
4
5
6
7
{
"compilerOptions": {
"module": "ES2015", // 或 "ES6", "ES2020", "ESNext"
"target": "ES2015"
}
}
bash
1
2
Uncaught SyntaxError: export declarations may only appear at top level of a module

这个错误是因为 export 语句出现在了非顶层作用域。ES Module 规范要求 export 语句只能在模块的顶层作用域使用。

原因是在 HTML 页面中通过普通的 <script> 标签引入了一个包含 ES6 模块导出(export)语法的 JavaScript 文件。浏览器要求使用模块化脚本(带有 type="module" 属性的 <script> 标签)才能处理含有 importexport 语句的代码。

CommonJS,AMDJS都是什么玩意?

开发环境搭建

1.生成一个项目

bash
1
2
npm init -y

2.安装依赖

bash
1
2
npm install -y typescript rollup rollup-plugin-typescript2 @rollup/plugin-node-resolve rollup-plugin-serve -D

在初次配置rollup时,遇到dist/bundle.js文件找不到问题,把我难坏了,原来rollup,一个端口可以对应public和dist两个根目录

rollup配置文件

format,可根据需要选择cjs,umd,esm,

选项为iife时,需要

config
1
2
3
4
5
6
7
format: 'iife', // 或者根据需要选择 'cjs', 'esm', 'umd' 等

关于ts的相关插件,加速开发

1.error lens,自带提示

学习ts的核心就是学习类型,使用类型规范化,在开发过程中及时发现错误,修改错误.

何时需要类型,在结果比较模糊时,显示添加类型可以强化安全.