最近新学TypeScript遇到的问题:
入口:index.ts:
import {AllpassConfig} from './type'
import xhr from "./xhr.js"
function allpass(config:AllpassConfig){
//toDO
xhr(config);
}
let conf = {
url : "192.168.0.198",
method : "get",
data : "data....",
}
allpass(conf);
export default allpass;
逻辑代码:
import { AllpassConfig } from "./type";
//在这个文件实现具体逻辑方法
export default function xhr(config:AllpassConfig){
const {data=null,url,method="get"} = config;
const req = new XMLHttpRequest();
console.log(method,url);
}
type 接口定义文件: type/index.ts
// 作为项目公共类型文件
export type Method = "get" | "GET" | "delete" | "DELETE" | "head" | "HEAD" | "POST" | "PUT" | "PATCH";
export interface AllpassConfig {
url : string;
method ?: string;
data ?: any;
params ?: any;
}
tsconfig.json 文件:
"moduleResolution": "node",
"target": "es5",
"module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"lib": ["es2015","dom"],
tsc 之后,然后加载到html中运行:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="module" src="./lib/index.js"></script>
</body>
</html>
去掉: type="module" 立马报错:
设置type
属性设为module
,浏览器就知道这是一个 ES6 模块。
浏览器对于带有type="module"的<script>,都是异步加载外部脚本,不会造成堵塞浏览器。