일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- PM2
- Tomcat
- Next.js
- Eclipse
- rocky9
- nodejs
- popup
- yona
- node.js
- jquery
- MSsql
- config
- git
- MariaDB
- ajax
- Java
- Push
- jenkins
- docker
- mysql
- spring3
- mybatis
- centos7
- security
- FCM
- NextJS
- SpringBoot
- Maven
- pwa
- javascript
- Today
- Total
ふたりで
vue.js To pwa (vue.js 프로젝트를 PWA 로...) 본문
준비물:
- vue ui
- 간단한 vue 토이 프로젝트 하나
* 나의 경우 기존에 vue.js 공부를 하느라 만들어본 사용자 인증 프로젝트에 PWA를 적용해 보았다.
대략 이틀정도 구글링을 하며 삽질하였다......
1. vue ui 에서 PWA를 설정할 프로젝트를 선택 한 다음 아래와 같이 PWA플러그인 설치
@vue/cli-plugin-pwa를 검색하여 설치해준다.
2. 의존성에도 register-service-worker 항목이 있는지 확인.
(없거나 정상인 상태가 아닌 경우 추후 service-worker.js 설정을 해주면 된다.)
3. 설정에서 아래와 같이 PWA 설정을 한다.(나는 앱 이름만 추가했다.)
4. VS-CODE로 본 프로젝트 구조
5. 위 3번 vue ui설정에서 앱 이름을 입력하고 저장하면 vue.config.js, registerServiceWorker.js,
public/manifest.json, public/index.html 그리고 public/img폴더 밑에 기본 아이콘들이 사이즈별로
생성된다.
6. registerServiceWorker.js 설정 수정.
registerServiceWorker.js 에서 front-end서버에서 올릴 건지 back-end서버 섭버에 올릴건지
아래와 같이 설정
/* eslint-disable no-console */
import { register } from 'register-service-worker'
/*process.env.node == '나중에 요청될 디렉토리 파일 이름'
* front server로 실행 할 경우 development
* back server와 같이 실행 할 경우 production
*/
if (process.env.NODE_ENV === 'development') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready () {
console.log(
'App is being served from cache by a service worker.\n' +
'For more details, visit https://goo.gl/AFskqB'
)
},
.
.
.
}
7. service-worker.js 작성.
6번 소스를 보면 service-worker.js 경로가 적힌 부분대로 컴파일 시 dist/service-worker.js 파일이 자동으로 생성된다.
자동으로 생성되는 service-worker.js관련해서는 좀 더 공부를 해봐야 할 것 같다.
중요: 개발환경의 경우 service-worker.js로 그대로 하면 안 되고 이름을 다르게 주어야 하는 것 같다.
나는 service-worker-dev.js로 이름을 변경하여 아래 소스와 같이 별도로 설정하였다.
6번의 registerServiceWorker.js 쪽도 service-worker-dev.js로 변경 해 주자.
참고: https://stackoverflow.com/questions/56074595/vuejs-service-worker-js-is-ignored-in-my-pwa/56075184
(서비스 워커 설정은 보통 아래와 같이 설정하느것 같다. service-worker관려하여 좀 더 공부가 필요하다.;;;;;;)
const CACHE_NAME = 'version-1';
// cache 목록 (캐싱할 목록 설정.)
const urlsToCache = [
'index.html',
'favicon.ico',
'css/*',
'img/*',
'js/*'
];
// cache 목록 등록, install상태시 cache 목록을 크롬cach에 저장한다.
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
// console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// keep fetching the requests from the user
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) return response;
return fetch(event.request);
})
);
});
self.addEventListener('activate', function(event) {
const cacheWhitelist = [];
// add cache names which you do not want to delete
cacheWhitelist.push(CACHE_NAME);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
8. manifest.json 설정.
vue ui 설정에서 앱 이름 작성 후 저장 시 자동으로 manifest.json이 만들어지긴 하나 아래와 같이 추가로 수정을 해준다.
나의 경우 scope옵션은 없어서 추가하였으며, scope, start_url의 값은 '/'로 설정해 주었다.
{
"name":"뷰PWA인증프로젝트",
"short_name":"뷰PWA인증프로젝트",
"theme_color":"#4DBA87",
"scope": "/",
"start_url":"/",
"display":"standalone",
"background_color":"#000000",
"icons":[
{"src":"./img/icons/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},
{"src":"./img/icons/android-chrome-512x512.png","sizes":"512x512","type":"image/png"},
{"src":"./img/icons/android-chrome-maskable-192x192.png","sizes":"192x192","type":"image/png","purpose":"maskable"},
{"src":"./img/icons/android-chrome-maskable-512x512.png","sizes":"512x512","type":"image/png","purpose":"maskable"}
]
}
9. public/index.html 수정.
index.html에 manifest.json 링크를 걸어준다.(<link rel="manifest" href="<%= BASE_URL %> manifest.json">)
<!DOCTYPE html>
<html lang="en">
<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">
<link rel="manifest" href="<%= BASE_URL %>manifest.json">
<title>vuejs jwt auth example</title>
<script>
// if ('serviceWorker' in navigator) {
// window.addEventListener('load', function () {
// navigator.serviceWorker.register('sw.js').then(function (registration) {
// // Registration was successful
// console.log('ServiceWorker registration successful with scope: ', registration.scope);
// }, function (err) {
// // registration failed :(
// console.log('ServiceWorker registration failed: ', err);
// });
// });
// }
</script>
</head>
<body>
<noscript>
<strong>We're sorry but genesis-web 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>
10. vue ui에서 build 하면 해당 프로젝트 폴더 내에(public폴더와 같은 위치에) 컴파일된 dist 폴더가 생성된다.
build가 완료되면 serve 항목에서 실행을 한 후 앱 열기 버튼을 놀러 PWA가 잘 적용되었는지 확인해본다.
11. PWA가 적용된 모습.
아래 그림에서 빨간 동그라미 친 부분을 누르면 설치 프로그램처럼 설치하여 웹 앱을 실행해 볼 수 있다.
12. 설치 프로그램으로 다운 로드하여 실행해본모습.
PWA가 어떤 건지 가볍게 접해 보았는데 결국 많은 작업을 해야 하는 건 front-end or back-end이다.
back-end야 springboot로 하며 된다 처도 front-end 관련하여 vue.js 공부를 본격 시작해 봐야겠다;;;;;;;;;;;;
'javascript' 카테고리의 다른 글
document.ready 이후 동적으로 생성된 Element에 event 걸기 (0) | 2021.12.10 |
---|---|
excelexportjs 사용시 숫자를 문자로 인식 시키기 (0) | 2021.12.09 |
multi iframe pageing print (동적 iframe 을 사용한 페이징처리 및 인쇄) (0) | 2021.07.05 |
동적 클릭 적용 및 클릭한 요소 내용을 dailog 창에 표시 하기 (0) | 2021.06.28 |
javascript 전화번호 휴효성 검사 (0) | 2021.03.30 |