npm init -y
로 초기화하면 package.json이 생성된다.
{
"name": "typechain",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
npm i -D typescript
타입스크립트 의존성을 추가해준다.
node_modules와 package-lock.json 또한 추가되는데, 프로젝트 레벨에 src폴더를 만들고 index.ts파일을 추가해준다.
또한 프로젝트 레벨에 tsconfig.json파일을 추가한다.
{
"include": ["src"],
"compilerOptions": {"outDir": "build"}
}
package.json의 scripts에 "build": "tsc"다음을 추가하고
npm run build로 실행하면
결과를 확인 할 수 있다.
컴파일된 js파일이 생성되었다.
var에 화살표 함수도 없다. tsconfig에 target을 추가해주고 ES6으로 설정해주고 다시 실행하면
{
"include": ["src"],
"compilerOptions": {
"outDir": "build",
"target": "ES6"
}
}
확인 가능하다.
"lib": ["ES6", "DOM"],
"_comment" : "ES6 - 브라우저 환경, DOM - document. 사용"
utills.js
function add(a, b){
return a+b;
}
utils.d.ts
declare function add(a: number, b: number): number;
tsconfig.json 파일에
"strict": true
다음을 추가해 스트릭트 모드로 바꿔주고,
src/myPackage.js파일을 생성해주고
export function init(config){
return true;
}
export function exit(code){
return code + 1;
}
index.ts파일에서 사용하려 한다면
import {init} from "myPackage";
타입스크립트는 아직 myPackage가 뭔지 몰라서 문제가 발생한다.
src에 myPackage.d.ts파일을 생성하면 myPackage가 뭔지 인식하고, init를 지정해주면 오류가 사라진다.
interface Config{
url: string;
}
declare module "myPackage"{
function init(config: Config): boolean;
}
//@ts-check
/**
* Initializes the project
* @param {object} config
* @param {boolean} config.debug
* @param {string} config.url
* @returns
*/
export function init(config){
return true;
}
/**
* Exits the program
* @param {number} code
* @returns
*/
export function exit(code){
return code + 1;
}
//@ts-check와 JSDoc을 활용해 js파일을 설정하고, tsconfig파일에 "allowJs": true 해주면
import {init, exit} from "./myPackage";
사용 가능