해당 포스트는 Node.js에 TypeScript 적용하기(feat. NodeBird) 강의로
typescript + nodejs
의 내용을 복습하며 필요한 내용을 정리한 포스트입니다.
🌈 직접 타입스크립트 라이브러리 만들기
💻 axios 만들기
axios 폴더 생성 후 npm init
1
2
npm init
npm i typescript
node환경에서도 axios사용이 가능하지만 이번에는 브라우저 환경용만 만들어본다.
🔻 pakagea.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "axios",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "leekoby",
"license": "ISC",
"dependencies": {
"typescript": "^5.2.2"
},
"types": "./index.d.ts"
}
🔻 tsconfig.json
1
2
3
4
5
6
7
{
"compilerOptions": {
"strict": true,
"declaration": true,
"lib": ["DOM", "ES2020"]
}
}
🔻 index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
export interface AxiosConfig {
headers?: {
[key: string]: string;
};
withCredentials?: boolean;
//쿠키 전달할 때 써야함
}
export interface AxiosData {
[key: string]: any;
}
export interface AxiosResult {
data: any;
status: number;
statusText: string;
}
//타입가드
function isAxiosData(data: any): data is AxiosData {
//데이터 is 리턴타입
if (data !== null) return false;
if (data instanceof FormData) return false;
return typeof data === 'object';
}
export interface Axios {
//data, config는 optional
defaults: {
baseUrl: string;
headers: {
[key: string]: string;
};
};
get(url: string, config?: AxiosConfig): Promise<AxiosResult>;
put(
url: string,
data?: string | AxiosData | FormData,
config?: AxiosConfig
): Promise<AxiosResult>;
patch(
url: string,
data?: string | AxiosData | FormData,
config?: AxiosConfig
): Promise<AxiosResult>;
post(
url: string,
data?: string | AxiosData | FormData,
config?: AxiosConfig
): Promise<AxiosResult>;
delete(url: string, config?: AxiosConfig): Promise<AxiosResult>;
options(url: string, config?: AxiosConfig): Promise<AxiosResult>;
head(url: string, config?: AxiosConfig): Promise<AxiosResult>;
}
const axios: Axios = {
defaults: {
baseUrl: '',
headers: {},
},
get(url, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('GET', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
xhr.send();
});
},
put(url, data, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('PUT', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
if (isAxiosData(data)) {
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
});
},
patch(url, data, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('PATCH', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
if (isAxiosData(data)) {
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
});
},
post(url, data, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('POST', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
if (isAxiosData(data)) {
xhr.send(JSON.stringify(data));
} else {
xhr.send(data);
}
});
},
delete(url, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('DELETE', axios.defaults.baseUrl + url);
const headers: { [key: string]: string } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
xhr.send();
});
},
options(url, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('OPTIONS', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
xhr.send();
});
},
head(url, config) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
resolve({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
} else {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
}
};
xhr.onerror = function () {
reject({
data: xhr.responseText,
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.open('HEAD', axios.defaults.baseUrl + url);
const headers: { [key: string]: any } = { ...axios.defaults.headers, ...config?.headers };
Object.keys(headers).map((key) => {
xhr.setRequestHeader(key, headers[key]);
});
xhr.withCredentials = config?.withCredentials || false;
xhr.send();
});
},
};
export default axios;
💻 라이브러리 빌드하기
브라우저에서 동작하게 작성했기 때문에 실행해보려고 하면 에러가 발생한다.
일반적인 상황은 아니지만 이를 해결하기 위해서 Webpack
과 Babel
을 사용한다.
강의에서는 awesome-typescript-loader
를 사용한다. 하지만 이 패키지의 경우 4버전 이상을 지원하지 않는 것으로 보인다.
현재 설치한 타입스크립트 버전이 5.2.2 버전이므로 ts-loader
패키지를 설치했다.
1
2
3
npm i webpack webpack-cli ts-loader
npm i @babel/preset-env @babel/core
npm i babel-plugin-add-module-exports
🔻 webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './index.ts',
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
use:{
loader:'babel-loader',
options:{
presets:['@babel/preset-env']
}
},
exclude:/node_modules/
}
],
},
output: {
path: path.join(__dirname),
filename: '[name].js',
libraryTarget:'umd'
},
resolve:{
extensions:['.ts','.js']
}
};
ts-loader
를 사용해서 강의와는 조금 다르게 설정해줬다.
원하는대로 올바르게 작동할 경우
npm publish
를 통해 배포할 수 있다. (npmjs에 가입되어있어야함.)