Skip to content

Commit 334338d

Browse files
committed
study: js module 시스템의 2가지 변경법(pacakge.json, tsconfig.json), ts-node 사용(-g)
1 parent 3ce0966 commit 334338d

File tree

8 files changed

+271
-25
lines changed

8 files changed

+271
-25
lines changed

EF-TS/ch01/01/01.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
"use strict";
2+
const states = [
3+
{ name: 'Alab', capital: "mont" },
4+
{ name: 'Alab', capital: "mont" },
5+
];
6+
for (const state of states) {
7+
console.log(state.capital);
8+
}

EF-TS/ch01/02/02.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"use strict";
2+
// function add(a, b) {
3+
// return a + b;
4+
// }
5+
// add(10, null);
6+
// ----------------------------------------------------------------
7+
// const x: number = null
8+
// ----------------------------------------------------------------
9+
const el = document.getElementById('status');
10+
// el.textContent = 'Ready'; Object is possibly 'null'
11+
if (el) {
12+
el.textContent = 'Ready'; // OK, null has been excluded, const el: HTMLElement
13+
}
14+
el.textContent = 'Ready'; // OK, we've asserted that el is non-null,
15+
// const el: HTMLElement | null, null이 아니라 단언했으니 htmlEle
16+
// !. 강제 형변환

README.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2132,6 +2132,35 @@ export = jQuery;
21322132
- `export default axios`로 되어 있다면 아래와 같이 `import` 가능
21332133
- `import axios from 'axios';`
21342134

2135+
#### Error
2136+
2137+
```ts
2138+
모듈 '"/Users/okpanda/git/Typescript-Study/axios"'에는 기본 내보내기가 없습니다.ts(1192)
2139+
// tsconfig.json에서 옵션 변경
2140+
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
2141+
(node:4703) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
2142+
// package.json 추가
2143+
"type": "module",
2144+
```
2145+
2146+
- `tsconfig.json`에서 `"module": "ES2022" -> "module": "CommonJS"` 설정을 바꾸어주어더니 `package.json`에서 추가한 `"type": "module",`때문에 에러가 났다.
2147+
2148+
- `Typescript는` 기본적으로 ES모듈을 지원하며, js의 모듈 시스템을 변경하는데(`ES` or `CommonJS`) 2가지 방법이 존재
2149+
- `package.json`에서 `'types'필드`를 사용하여 바꿀 수 있음.
2150+
- `"type": "module"``ES 모듈 시스템`을 사용하고 있음을 나타내며, `"type": "commonjs"``CommonJS 모듈 시스템`을 사용하고 있음을 나타냄
2151+
- `tsconfig.json: "module"` 필드를 사용하여 `TypeScript` 컴파일러에게 `JavaScript` 파일을 어떤 모듈 형식으로 생성할지 지시할 수 있다.
2152+
- `"module": "ES2022"``ES 모듈 시스템`을 사용하여 `JavaScript` 파일을 생성하고, `"module": "CommonJS"``CommonJS 모듈 시스템`을 사용하여 `JavaScript` 파일을 생성
2153+
2154+
- `"package.json"` 파일에서 `"type": "module"`을 추가하는 것은 해당 프로젝트가 `ES 모듈 시스템`을 사용한다는 것을 명시하는 것
2155+
2156+
- 이것은 `Node.js`에서 기본적으로 `CommonJS` 모듈 시스템을 사용하는 것과는 다르다.
2157+
2158+
- `ES 모듈 시스템``"import"``"export"` 구문을 사용하여 모듈을 가져오고 내보내는 데 사용된다. 반면에 `CommonJS` 모듈 시스템은 `"require"``"module.exports"`를 사용한다.
2159+
2160+
- 따라서 `"type": "module"`을 추가하면 해당 프로젝트의 `JavaScript` 파일은 `ES 모듈 시스템`의 규칙을 따르게 되며, `"import"` 구문을 사용하여 외부 패키지를 가져올 수 있다. 그래서 `"axios"`와 같은 패키지를 `"import"`를 사용하여 가져올 수 있게 된다.
2161+
2162+
- `"ReferenceError: exports is not defined in ES module scope"`와 같은 오류는 `CommonJS 모듈 시스템`을 사용할 때 발생하는 오류로, `"exports"`라는 변수가 ES 모듈 시스템에서는 정의되어 있지 않기 때문에 발생, `"type": "module"`을 추가하면 `Node.js``ES 모듈 시스템`으로 인식하므로 `CommonJS` 관련 오류가 발생할 수 있다.
2163+
21352164
### 다양한 방식으로 사용 가능한 axios
21362165

21372166
- 브라우저(), node 양측에서 요청을 보낼 떄 사용 가능
@@ -2206,3 +2235,61 @@ export class Axios {
22062235
- `axios();`
22072236
- `axios.get();`
22082237
- `axios.get;` `axios.delete;``class Axios`에 들어있다.
2238+
2239+
axios.ts
2240+
2241+
```ts
2242+
import axios from "./node_modules/axios/index";
2243+
2244+
(async () => {
2245+
try {
2246+
const res = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
2247+
console.log(res);
2248+
} catch (error) {}
2249+
})();
2250+
```
2251+
2252+
axios.js
2253+
2254+
```js
2255+
"use strict";
2256+
var __importDefault =
2257+
(this && this.__importDefault) ||
2258+
function (mod) {
2259+
return mod && mod.__esModule ? mod : { default: mod };
2260+
};
2261+
Object.defineProperty(exports, "__esModule", { value: true });
2262+
const axios_1 = __importDefault(require("axios"));
2263+
(async () => {
2264+
try {
2265+
const res = await axios_1.default.get(
2266+
"https://jsonplaceholder.typicode.com/posts/1"
2267+
);
2268+
console.log(res);
2269+
} catch (error) {}
2270+
})();
2271+
2272+
🟠response
2273+
2274+
export interface AxiosResponse<T = any, D = any> {
2275+
data: T;
2276+
status: number;
2277+
statusText: string;
2278+
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
2279+
config: InternalAxiosRequestConfig<D>;
2280+
request?: any;
2281+
}
2282+
```
2283+
2284+
tsconfig.json
2285+
2286+
```ts
2287+
"module": "ES2022" -> "module": "CommonJS"
2288+
```
2289+
2290+
- js변환(`npx tsc`), `node axios.js`가 귀찮으면, `npm i -g ts-node`
2291+
- `-g`옵션을 통해 `npx ts-node axios`가 아닌 `ts-node axios`가 가능
2292+
- `npx는` `npm` 패키지를 실행하는 데 사용되는 도구
2293+
- 일반적으로 npm 패키지를 전역으로 설치하지 않고 특정 프로젝트에서만 사용하려는 경우에 사용, npx를 사용하면 로컬 프로젝트에 설치된 패키지를 간단하게 실행할 수 있다.
2294+
- `npx를` 사용하면 전역 설치된 패키지를 찾아 실행할 필요가 없으며, 로컬 프로젝트의 패키지를 사용할 때 편리, 만약 전역으로 ts-node를 설치했다면 npx를 사용하지 않고 ts-node axios.ts로 실행할 수 있다.
2295+
- `__importDefault`: CommonJS랑 ES2015Module 둘 다 지원하기 위한 트릭

axios.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"use strict";
2+
var __importDefault =
3+
(this && this.__importDefault) ||
4+
function (mod) {
5+
return mod && mod.__esModule ? mod : { default: mod };
6+
};
7+
Object.defineProperty(exports, "__esModule", { value: true });
8+
const axios_1 = __importDefault(require("axios"));
9+
(async () => {
10+
try {
11+
const res = await axios_1.default.get(
12+
"https://jsonplaceholder.typicode.com/posts/1"
13+
);
14+
console.log(res);
15+
} catch (error) {}
16+
})();

axios.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1-
import axios from "./node_modules/axios/index";
1+
import axios from "axios";
22

3-
axios.get;
3+
(async () => {
4+
try {
5+
const res = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
6+
console.log(res.data);
7+
} catch (error) {}
8+
})();

first.js

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,31 @@
11
"use strict";
2-
let a = 'hello';
3-
a = 1234;
4-
// 에디터가 자동으로 타입검사를 해준다. ctrl+`: 터미널 열기
5-
// tsc --noEmit하면 처음에는 터미널이 알아듣지 못한다. 이떄 node를 사용🟢 tsc컴파일러를 설치해야 된다.
6-
// 1. npm init -y : package.json이 생김, Typescript-Study폴더가 node 프로젝트가 됨
7-
// node 프로젝트의 설정을 모아둔 곳이 package.json, 이제 npm 명령어들을 프로젝트에서 사용가능🟢
8-
// 2. npm i typescript : typescrpt 설치, npm은 node의 프로그램들 정확히 말하면 node의 package라고 부르는데,
9-
// node의 프로그램들을 모아두는 저장소를 npm이라는 node package mananger가 있다.
10-
// 그러면 현재 npm안에 저장되어 있는 typescrpt를 설치한 것이다.
11-
// 이제 tsc를 쳐보면 안된다.(?) 앞에 npx를 붙여야 한다. 그러면 사용할 수 있는 명령어들이 나온다.
12-
// 3. npx tsc --init : tsconfig.json이라는 파일이 생긴다.
13-
// tsconfig.json📗
14-
// 🟢Typescript 프로젝트 시작할때 package.json, tsconfig.json 이 두 파일을 만들고 시작해야 하고, tsconfig.json 읽을 줄도 알아야 한다.
15-
// 😨아직 ts가 서툴다면 tsconfig.json에서 "allowJs": true 옵션을 주석해제 하자, js와 ts 동시사용 가능, 그 상태에서 js-> ts 전환
16-
// "target": "es2016" -> tsc가 나의 코드를 es2016으로 바꿔줌.
17-
// "module": "commonjs" -> js에서 module system은 흔하다, import, export || require, module exports
18-
// "module": "ES2015"나 "ES2022"는 같다, 최신 모듈 시스템 쓰고 싶으면 "ES2015"✅, node 모듈 시스템 쓰고 싶으면 "commonJs"✅
19-
// 🟢strict: true 고정 ! 나중에 필요할 떄 tsconfig.json 수정할 수도 !
2+
/*
3+
에디터가 자동으로 타입검사를 해준다. ctrl+`: 터미널 열기
4+
tsc --noEmit하면 처음에는 터미널이 알아듣지 못한다. 이떄 node를 사용🟢 tsc컴파일러를 설치해야 된다.
5+
1. npm init -y : package.json이 생김, Typescript-Study폴더가 node 프로젝트가 됨
6+
node 프로젝트의 설정을 모아둔 곳이 package.json, 이제 npm 명령어들을 프로젝트에서 사용가능🟢
7+
8+
2. npm i typescript : typescrpt 설치, npm은 node의 프로그램들 정확히 말하면 node의 package라고 부르는데,
9+
node의 프로그램들을 모아두는 저장소를 npm이라는 node package mananger가 있다.
10+
그러면 현재 npm안에 저장되어 있는 typescrpt를 설치한 것이다.
11+
12+
이제 tsc를 쳐보면 안된다.(?) 앞에 npx를 붙여야 한다. 그러면 사용할 수 있는 명령어들이 나온다.
13+
14+
3. npx tsc --init : tsconfig.json이라는 파일이 생긴다.
15+
16+
📗tsconfig.json📗
17+
🟢Typescript 프로젝트 시작할때 package.json, tsconfig.json 이 두 파일을 만들고 시작해야 하고, tsconfig.json 읽을 줄도 알아야 한다.
18+
😨아직 ts가 서툴다면 tsconfig.json에서 "allowJs": true 옵션을 주석해제 하자, js와 ts 동시사용 가능, 그 상태에서 js-> ts 전환
19+
"target": "es2016" -> tsc가 나의 코드를 es2016으로 바꿔줌.
20+
"module": "commonjs" -> js에서 module system은 흔하다, import, export || require, module exports
21+
"module": "ES2015"나 "ES2022"는 같다, 최신 모듈 시스템 쓰고 싶으면 "ES2015"✅, node 모듈 시스템 쓰고 싶으면 "commonJs"✅
22+
🟢strict: true 고정 ! 나중에 필요할 떄 tsconfig.json 수정할 수도 !
23+
🟢"forceConsistentCasingInFileNames": true => ts에서는 모듈 시스템이 있어서 다른 파일을 import 가능, 윈도우는 대소문자 구분 크게 신경❌
24+
but mac이나 리눅스는 대소문자를 구분하기에 대소문자로 에러가 날 수 있음, 대소문자 지켜서 import하도록하는 옵션
25+
🟢"skipLibCheck": true -> 라이브러리 check를 건너띄운다, 다른 package들을 다운받아서 사용할 떄 그 package들에 전부 .d.ts라는 파일이 있다.
26+
.d.ts 는 그 package에 type을 정리해둔 파일, 실제 사용하는 타입만 검사하도록, 안쓰는 타입 검사❌
27+
28+
4. npx tsc --noEmit : 타입 검사한 내역이 터미널에 뜬다.
29+
5. npx tsc : ts파일을 -> js파일로 변환하여 생성
30+
🟢 타입 검사 기능과 코드 변환 기능은 별개로 돌아간다.
31+
*/

jquery.js

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
"use strict";
2+
// import $ from 'jquery';
3+
// export { }
4+
// 위처럼 import 문, export문의 유무에 따라서 이 파일이 어떻게 인식되는지가 달라진다.
5+
// 있다면 module 시스템으로 인식하고 없다면 전역 스크립트로 인식한다.
6+
// 전역 스크립트로 인식되는 경우 이 파일에서 작성한 타입들이 다른 파일에 있을 것이라고 생각하고
7+
// 에러가 안뜨게 된다. 그래서 괜히 모듈 시스템으로 만들어서 타입이 꼬이는 경우가 있다.
8+
var _a;
9+
$("p").removeClass("myClass noClass").addClass("yourClass"); // 1️⃣
10+
$("p").removeClass(["myClass", "noClass"]).addClass("yourClass"); // 2️⃣
11+
$("p")
12+
.removeClass((index, className) => {
13+
return "myClass";
14+
})
15+
.addClass("yourClass"); // 3️⃣
16+
/*
17+
removeClass(
18+
className_function?:
19+
| JQuery.TypeOrArray<string> 🔥
20+
| ((this✅: TElement, index: number, className: string) => string),
21+
): this;
22+
TS에서 첫 번째 매개변수가 this인 경우, 없다고 생각하면 된다.
23+
$("p").removeClass((index, className) => {
24+
return 'myClass';✅
25+
}).addClass("yourClass");
26+
27+
type TypeOrArray<T> = 🔥 T | T[]; 🔥
28+
29+
$("p").removeClass("myClass noClass").addClass("yourClass");
30+
$("p").removeClass(["myClass", "noClass"]).addClass("yourClass");
31+
*/
32+
const $p = $("p");
33+
$p.removeClass("myClass noClass").addClass("yourClass");
34+
(_a = document.querySelector("h1")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", function () {
35+
console.log(this); // this='h1'
36+
});
37+
/*
38+
removeClass -> addClass 메서드 체이닝
39+
removeClass의 return값은 this
40+
$p.removeClass:this -> $p가 되고 아래처럼 된다.
41+
$p.addClass('yourClass');
42+
addClass(
43+
className_function:
44+
| JQuery.TypeOrArray<string>
45+
| ((this: TElement, index: number, currentClassName: string) => string),
46+
): this;
47+
addClass또한 return값이 this🔥
48+
*/
49+
// jquery에서, $ -> 변수(혹은 _)
50+
$(["p", "t"]).text("hello");
51+
/*
52+
interface PlainObject<T = any> {
53+
[key: string]: T;
54+
} 아무거나 가능
55+
56+
text(
57+
text_function:
58+
| string
59+
| number
60+
| boolean
61+
| ((this: TElement, index: number, text: string) => string | number | boolean),
62+
): this;
63+
$(["p", "t"]).text(()=> {
64+
console.log(this); // this: string[]
65+
return 'hello';
66+
});
67+
함수 안에 존재하는 함수의 this는 상위에 있는 것을 그대로 받아오기 때문에 화살표 함수로 만들어 주는 것이 좋다.
68+
*/
69+
const tag = $("ul li")
70+
.addClass("hello")
71+
.addClass(function (index) {
72+
return "item-" + index;
73+
});
74+
$(tag).html(function (i) {
75+
console.log(this);
76+
return $(this).data("name") + "입니다";
77+
});
78+
const div = document.createElement("div");
79+
div.innerHTML = "hello";
80+
const div1 = document.createDocumentFragment();
81+
$(tag).html(div); // const div: HTMLDivElement < Element
82+
$(tag).html(div1); // const div1: DocumentFragment
83+
// interface에서 this는 자기 자신을 가르키며, 첫 번쨰 param이 this인 경우 타이핑이 이미 존재
84+
const $tag = $([
85+
"p",
86+
"t",
87+
]);
88+
$tag.text("123");
89+
$tag.text(123);
90+
$tag.text(function (index) {
91+
console.log(this, index);
92+
return true;
93+
});
94+
$tag.text().html(document);
95+
const tagType = $("ul li")
96+
.addClass("hello")
97+
.addClass(function (index) {
98+
return "item-" + index;
99+
});
100+
$(tagType).html(document);
101+
// 유사배열, querySelectorAll같은것들

tsconfig.json

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
/* Language and Environment */
1414
"target": "es2017" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
1515
"lib": [
16-
"es2020", "dom"
16+
"es2020",
17+
"dom"
1718
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
1819
// "jsx": "preserve", /* Specify what JSX code is generated. */
1920
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
@@ -27,9 +28,9 @@
2728
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
2829

2930
/* Modules */
30-
"module": "ES2022" /* Specify what module code is generated. */,
31+
"module": "CommonJS" /* Specify what module code is generated. */,
3132
// "rootDir": "./", /* Specify the root folder within your source files. */
32-
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
33+
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
3334
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
3435
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
3536
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
@@ -79,8 +80,8 @@
7980

8081
/* Type Checking */
8182
"strict": true /* Enable all strict type-checking options. */,
82-
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
83-
"strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
83+
"noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */,
84+
"strictNullChecks": true /* When type checking, take into account 'null' and 'undefined'. */,
8485
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
8586
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
8687
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */

0 commit comments

Comments
 (0)