学习typescript(二)
2024-09-01 07:23:06
学习typescript(二)
ts 与 js 交互
ts 调用 js
module使用
分为两种情况:
ts
调用自己写的js
ts
调用别人写的js
也就通过npm
安装的
第一种情况处理如下:
tsconfig.json
的compilerOptions
中加入"allowJs": true
选项- 在任何一个
ts
文件中加入declare function require(path: string): any;
, 使用require
语法,例如:const test = require('./test2')
- 另一个使用方法,直接使用
ts
的导入语法:import test = require('./test2)
第二种情况处理如下:
跟第一种方法类似进行处理。
global
node
中有一个全局变量 global
和 module.exports
怎样使用呢?
解决方案:
在 ts
加入如下:
declare var module: any;
declare var global: any;
就可以正常使用
js 调用 ts
js
不能直接 ts
,而 ts
能直接调用 js
,js
能调用 ts
的编绎成果.
这其中关键是 js
与 ts
的模块系统编绎结果之间的问题。
// ts 语法
export const test1 = (x) => x + 1
// exports.test1 = (x) => x + 1 cmd
export default const test2 = (x) => x + 1
// export default const test2 => x => x + 1 es6 语法
// 注意: es6语法 import 是的 node 环境中无法使用的
export {
foo as foo1,
foo1 as foo2
}
// 上面等于 js 语法
// exports.foo1 = foo
// exports.foo2 = foo1
// 对 export 赋值
const f1 = () => console.log(1)
const f2 = () => console.log(1)
const f3 = () => console.log(1)
export = {
f1,
f2,
f3
}
// 不过上面这种语法别的 `ts文件导入时需使用`
import ts = require('bluebird')
// es6
//exports = {
// f1,
// f2,
// f3
// }
import daf from 'bluebird' // 这种语法只适合有 default 导出的方法
总结
ts
的语法是使用 import from
,这个语法有独特的行为, 表现在会针对 default
进行处理。
- 如果被导入的文件没有使用
default
,那只能使用import * as from
语法 - 如果被导入的文件使用了
default
,import xxx from
语法就是把默认导出对象赋值给xxx
ts
语法基本上跟es6
的一致。- default 也能正常使用,但是与编绎结果与正常的
js
交互会有问题,因此不能使用default
。
所以, ts
模块系统使用原则:
- 永远只在
ts
内部使用export default
- 在
ts
调用js
时使用import * as XXX
或者使用构析语法import {xxx} from '.xxx'
ts
调用js
时, 如果想使用js
提示的话使用import
语法- 如果不想使用提示,使用
require
语法。
js
使用原则:
- 导出模块只这样使用
module.exports
最新文章
- Cosmos —— Big Data at Microsoft
- 11. KVC And KVO
- 模板函数 使用的默认void 模板报错
- Windows Azure 云服务角色架构
- [问题2014S12] 复旦高等代数II(13级)每周一题(第十二教学周)
- sublime福音:微信小程序组件及API补全插件
- 什么是J2EE,包括哪些规范!
- linux下忘记mysql root密码解决办法
- 1203.2——条件语句 之 switch语句
- 常用python处理try except异常的三种方式
- Android如何监听蓝牙耳机的按键事件(转)
- Cocos2D场景中对象引用为nil时的判断
- Java:配置环境(Mac)——JDK
- Luogu P5168 xtq玩魔塔
- iOS 判断当前网络状态的三种方法
- CSS基础入门
- ubuntu 16.04 安装中文语言包
- 推荐两个小工具MediaInfo 和 netpersec
- css笔记 - animation学习笔记(二)
- .NET压缩图片保存