typescript json import

tsconfig.json
1
2
3
4
5
6
{
"compilerOptions": {
// (...)
"resolveJsonModule": true
}
}
  • tsconfig.jsoncompilerOptions 부분에 resolveJsonModule를 추가한다
ex.ts
1
import myJsonData from './myJson.json';
  • 이런식으로 가져다 쓸 수 있다

참고

ts-node

terminal
1
ts-node src/index.ts
  • tsc를 통해 .js파일로 만들고, js파일을 실행하는 것이 아니라
  • 바로 .ts 파일을 실행하는 것처럼 보여준다
  • 따로 .js파일은 생성되지 않는다

ts-node 설치

terminal
1
npm install -g ts-node

참고

Banner Maker 클론코딩

데모

기능

  • 캔버스 크기 조절
  • 실시간 캔버스 업데이트
  • 폰트 사이즈 조절
  • 폰트색 조절
  • 캔버스색에 따른 폰트색 자동조절
  • 캔버스색 조절
  • 랜덤 캠버스색
  • 이미지로 다운로드
  • 클립보드로 카피
  • 컬러 히스토리 기능
  • 컬러 히스토리 임포트, 익스포트 기능

후기

  • 타입스크립트 공부 겸 리액트도 같이 하자는 생각으로 리액트 타입스크립트를 시작했다
  • velopert님의 리액트 프로젝트에서 타입스크립트 사용하기 글을 보고 따라하다가
  • 튜토리얼을 통해 잘 만들어진 프로젝트 구조를 기반으로 만들었다
  • 리액트가 아직 익숙하지 않은데 리액트의 훅이라던지 처음부터 고급??개념들을 사용하니까
  • 사실 뭐가 좋은지, 이렇게 써서 좋은점이 무엇인지..
  • 이 개념을 도입하기전의 것들을 시도해보지 않았기 때문에 막연한 감이 있었다
  • 나는 공부할때 이론보단 무조건 실기이고, 일단 만들어보면서 익히고 이해하자라는 주의이다
  • 그래서 이것저것 쉽게만들 수 있다고 생각한다. (나중에 보면 코드가 엄청 구릴지라도..)
  • 이번에 만들면서 신경썼던 것은
  • 사용성..?? 인 것같다

  • 나는 보통 이미지를 ctrl c 카톡에다가 ctrl v 하여 톡방에 올리는데
  • 그걸위한 copy clipboard 버튼을 만들었다. 저장후 이미지 올리기는 귀찮기 때문에..

  • 또 랜덤 칼러 버튼을 만들어서 색을 쇼핑했다
js/index.jshtml-banner-maker/commit/5cccc1594309f732ea8edd8ca08c91800d97d317
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// https://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color
/**
* Get color (black/white) depending on bgColor so it would be clearly seen.
* @param bgColor
* @returns {string}
*/
function getColorByBgColor(bgColor) {
if (!bgColor) {
return '';
}
return parseInt(bgColor.replace('#', ''), 16) > 0xffffff / 2
? '#000'
: '#fff';
}
  • 사용해보면 알겠지만 랜덤으로 생성된 배경색에 따라 폰트색도 검정색/흰색 적절한게 선택된다

  • 컬러 히스토리 기능이다
  • copy 버튼이나 download 버튼을 누르면 해당 배경색과, 폰트색이 히스토리에 저장된다
  • 만약에 같은 최근 히스토리에 저장된 색과 같은 색이면 저장하지 않도록 하였다. 버튼을 누를때마다 증식되지 않도록..
  • export 버튼을 눌러 현재 저장된 컬러 히스토리를 json 파일로 내보내는 기능도있다
  • 깃허브 페이지를 이용해 호스팅하기때문에, 내 앱은 정적이다
  • 어떻게 히스토리를 저장하고 불러올까 생각하다가 json 파일로 내보내고 다시 불러오도록 만들게 되었다

개선방향

  • 칼러픽커에서 알파값을 바꿀 수 있도록 하기
  • 폰트 변경 기능
  • textarea를 div안에 넣어버리기..? (html2canvas 사용해보기)
  • json파일로부터 컬러히스토리 임포트할때 덮어쓰기가 아니라 병합으로 불러오기
src/modules/common/copyToClipboard.js
1
2
3
4
5
6
7
8
9
10
11
export function copyToClipboard() {
const canvas = document.querySelector(`#myCanvas`);
if (!canvas) {
return;
}
canvas.toBlob(function (blob) {
// eslint-disable-next-line no-undef
const item = new ClipboardItem({ 'image/png': blob });
navigator.clipboard.write([item]);
});
}
  • 클립보드 복사 js 코드를 ts로 변환하지 못한 코드..

소스코드

참고

TypeDoc 시작하기

따라하기

TypeDoc 생성하기

샘플 코드 작성

package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"name": "typedoc-practice",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"tsc": "tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"typedoc": "^0.19.2",
"typescript": "^4.0.3",
"typedoc-plugin-nojekyll": "^1.0.1"
},
"dependencies": {}
}
  • 연습용 디렉터리를 생성하고 위 내용으로 package.json을 생성한다
cmd
1
npm i
  • 종속성을 설치한다
tsconfig.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "*": ["types/*"] },
"target": "ES3",
"module": "commonjs",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
"typedocOptions": {
"mode": "modules",
"out": "docs"
}
}
  • 타입스크립트 설정파일 tsconfig.json를 생성한다
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
/**
* This class keeps track of the version number
* of your application.
*/
class Status {
/**
* This property ...
*/
public version: number = 0;

/**
* This method prints out the current version number
*/
public showVersion() {
console.log('version:', this.version);
}

/**
* This method increases the version number with 1
*
* @returns the current version number
*/
public increaseVersion() {
this.version += 1;
return this.version;
}

/**
* change the version number to the provided number
*
* @param version the number that needs to be used as a version number
* @returns the current version number
*/
public changeVersion(version: number) {
this.version = version;
return this.version;
}
}
  • index.ts를 생성하고, 독주석을 작성한다
  • 나는 Typescript: generate documentation를 참고하여 작성하였다
  • javaDoc과 동일한 문법으로 작성하면된다
  • 독주석을 작성하고싶은 클래스나 메서드, 변수 위에 /**를 타입하면 독주석 자동완성이 나온다
  • 자동완성으로 만들경우에 @param, @returns가 자동완성된다

typedoc 생성하기

  • 이제 문서를 생성해보자
cmd
1
npx typedoc --out docs
  • docs라는 폴더가 생긴다
  • docs/index.html 파일을 열어서 잘 만들어졌는지 확인한다
  • 이제 깃허브에서 볼 수 있도록 해보자

깃허브에 올리기

  • 처음 package.json에 보면 typedoc-plugin-nojekyll 모듈을 설치해줬는데,
  • 기본적으로 깃허브 페이지는 지킬 기반으로 동작한다
  • 지킬에는 어떤 규칙이 있는데 _로 시작하면 페이지가 안나온다
  • typedoc을 통해 생성된 html은 _index_.html 이런식으로 _가 붙는다
  • 따라서 docs/ 디렉터리에 지킬을 사용하지 않는다는 것을 알리는 .nojekyll이라는 파일을 만들어놔야한다
  • 수동으로 .nojekyll을 추가할 수 있지만, npx typedoc --out docs명령을 쓸때마다 초기화되서 불편하다
  • typedoc-plugin-nojekyll 모듈은 이 문제를 해결해준다

.gitignore 추가

.gitignore
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
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# End of https://www.toptal.com/developers/gitignore/api/node
  • .gitignore 파일을 만든다. node프로젝트용 무시목록이다

  • 깃허브에 저장소를 만들고 푸쉬한다

  • 저장소 > 세팅
  • master, docs 선택하고 save버튼을 누른다
  • 생성된 링크를 클릭해서 잘 동작하는지 확인한다

여기까지 소스코드

리액트로 네이버 퍼센트 계산기 클론코딩

  • 막 배운 리액트로 처음 만들어본 프로젝트이다
  • 계산하기 귀찮아하는 나는 평소 네이버 퍼센트 계산기를 이용했었는데
  • 이 계산기를 리액트를 사용해 클론코딩해보자..

데모

후기

  • 내가 너무 간단한 것을 만들어서 그런지 모르겠지만
  • 리액트를 처음 써본 내 기준으로 너무 복잡하다고 느껴졌다
  • 기존에 html, css, js로 만들때 보다 시간이 배로 걸렸다
  • 나중에 훨씬 복잡한 것을 만들게 되었을 때 리액트가 좋다고한다
  • 이미 잘 만들어진 리액트 튜토리얼을 따라만들고, 수정하는 방식으로 만들었다
  • 사용한 개념에 대해 완전히 이해하고 익숙해지는데 시간이 필요할 것 같다

소스코드

  • react-percentage-calculator
  • README.md에 리액트로 만든 화면을 깃허브 페이지로 보여주는 방법 등 메모해놨다