
getPosts.ts
import axios from 'axios';
export async function getPosts() {
try {
const response = await axios({
method: 'GET',
url: 'http://localhost:3001/posts',
});
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
return null;
}
}

ts-node와 필요한 패키지 설치npm i -g ts-node
npm i -g typescript
npm i -D tslib @types/node
tsconfig.json에 아래 코드 추가ts-node를 통해 코드를 실행할 때만 "module": "commonjs**"**를 사용하도록 설정"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
}
import axios from 'axios';
export async function getPosts() {
try {
const response = await axios({
method: 'GET',
url: 'http://localhost:3001/posts',
});
console.log(response.data);
return response.data;
} catch (error) {
console.error(error);
return null;
}
}
getPosts(); // 추가



References
ts-node 로 TypeScript (*.ts)파일 실행하기 Unknown file extension ".ts"
Typecript 에서 Cannot use import statement outside a module 에러 해결