[Vue CLI 4] static 파일 사용하기
2022-03-31
- Vue CLI 4
- Vue3
- static file
- axios
- env
- json
- markdown
이전 포스팅 - Vue CLI 4 마크다운 파일을 불러와 HTML로 변환하기
이전에 나는 md파일을 import
하기 위해 webpack
에서 md파일에 대한 loader
설정을 했었다.
또 loader
설정을 위해 raw-loader
라는 패키지도 설치했었다.
그렇다 보니 빌드를 하게되면 해당 md
파일을 js
파일로 컴파일 후 배포하는 과정을 거치게 된다.
따라서 static
파일들은 불필요한 컴파일 과정을 거치지 않도록 public
폴더로 옮기고 파일 호출 로직을 변경하려고 한다.
static 파일은 public 폴더로
🔎
public
폴더 ?
static
파일들을 위해Vue CLI
에서 제공하는 폴더이다. Vue 프로젝트를 생성하면 root 경로에 자동으로 함께 생성된다.Webpack
영향 범위에 들어가지 않고build
후에output > directory
에 그대로 복사된다.public
폴더에 있는 파일들은HTTP
요청을 통해 사용할 수 있다.
static
파일인 md
, json
을 public
폴더로 옮긴다.
옮긴 폴더 구조는 아래와 같다.
ㄴ src
ㄴ public
ㄴ posts
ㄴ images
ㄴ post-image.jpg
ㄴ index.json
ㄴ post.md
ㄴ index.html
ㄴ favicon.ico
Axios를 이용해 Static 파일 호출하기
public
폴더로 옮긴 static
파일은 http
요청을 통해 사용한다.
HTTP
요청에 사용할 axios
를 설치한다.
yarn add axios
🔎
axios
?
- 뷰에서 권고하는 HTTP 통신 라이브러리
- Promise 기반
- 상대적으로 다른 HTTP 통신 라이브러리들에 비해 문서화가 잘되어 있고 API가 다양하다.
- JSON 데이터 자동 변환
Main.vue
와 PostDetail.vue의
import
구문을 axios
로 아래와 같이 변경했다.
📃 src/router/views/Main.vue
<template>
<container-comp>
<post-list :posts="posts" />
</container-comp>
</template>
<script>
import axios from 'axios'
import ContainerComp from '@/components/layout/Container.vue'
import PostList from '@/components/PostList.vue'
export default {
components: {
ContainerComp,
PostList
},
data() {
return {
posts: [],
baseUrl: process.env.VUE_APP_BASE_URL,
}
},
created() {
axios.get(`${this.baseUrl}/posts/index.json`)
.then(res => this.posts = res.data)
.catch(e => console.log(`ERROR🙄 ${e.response.status} : ${e.request.responseURL}`))
}
}
</script>
📃 src/router/views/PostDetail.vue
<template>
<div v-html="contents"></div>
</template>
<script>
import axios from 'axios'
import htmlConverter from "@/utils/htmlConverter";
export default {
data() {
return {
contents: null,
baseUrl: process.env.VUE_APP_BASE_URL,
}
},
created() {
const param = this.$route.params.title
axios.get(`${this.baseUrl}/posts/${param}.md`)
.then(res => this.contents = htmlConverter(res.data))
.catch(e => console.log(`ERROR🙄 ${e.response.status} : ${e.request.responseURL}`))
},
}
</script>
여기서 process.env.VUE_APP_BASE_URL
은 환경 설정 파일에 내가 설정한 base url이다.
baseUrl
없이 axios.get(`/posts/index.json`)
로 입력해도 json 파일을 호출할 수 있긴하나 baseUrl을 삽입하는것을 추천한다고 한다.
환경 설정은 루트 경로에 .env파일을 생성해 작성 할 수 있다.
환경 파일 설정하기
🔎
.env
?
- 환경 설정 변수들을 지정하여 어플리케이션 로직, 웹팩 빌드 옵션에 활용할 수 있다.
- 환경 설정 변수를 활용하기 위해서는 webpack에 추가 설정이 필요하나, Vue Cli 3 이상부터는 변수 앞에
VUE_APP_
를 붙여주면 Vue Cli가 자동으로 설정해준다.- 종류
- .env : 모든 케이스에 적용
- .env.local : 모든 케이스에 적용, git에서는 제외됨
- .env.[mode] : 특정 모드에서만 적용 (development / test / production)
- .env.[mode].local : 특정 모드에서만 적용, git에서는 제외됨
따라서 나는 로컬에서만 사용할 .env.local
과 .env.production
파일 두개를 생성해 아래와 같이 작성했다.
📃 .env.local
VUE_APP_TITLE=local | DEV BLOG
VUE_APP_BASE_URL=http://localhost:6060
PORT=6060
📃 .env.production
VUE_APP_TITLE=DEV BLOG
VUE_APP_BASE_URL=https://sssjsjj.github.io
나는 VUE_APP_TITLE
도 지정해놨는데 public/index.html
에서 title
값을 해당 변수명으로 아래와 같이 지정해주면 사이트 타이틀값이 해당 변수 값으로 적용된다.
📃 public/index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= VUE_APP_TITLE %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= VUE_APP_TITLE %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
이렇게 static
파일들을 axios
로 가져오도록 로직을 변경하고,
더이상 필요없어진 raw-loader
패키지를 제거하고 vue.config.js
에 관련 설정을 제거해줬다.
Next
HTTP 요청을 위해 컴포넌트 마다 axios를 import하고있다.
또 PostDetail.vue에서도 현재는 md만 내용을 가져왔지만, 포스팅의 정보도 상단에 표시해야하기때문에 특정 포스팅의 정보를 가져와야한다.
그렇게 되면 Main.vue와 겹치는 로직이 더 많아지게된다.
따라서 다음 포스팅에서는 HTTP 요청 관련 모듈을 만들어보려고 한다.
수정이 필요한 부분 혹은 더 나은 방법을 알고계신가요?
댓글로 알려주시면 저에게 큰 도움이 됩니다! 😊💜