個人でPWA作るのは好きなのですが、レンタルサーバだと大概 Node.js
に対応しないので、いろいろためらってたのですが、 Vue-cli
を使えば解決することがようやく解ったので、環境の作り方などを書き置きします。
Vue-cliにするとどうなる?
CDNを利用すると、まれにWebpack
(Webアプリの最適化を行うもの)のバージョン違いなどにより Vueコンポーネント
を直接使えなかったりする制約が出てくるのですが、普通にVue.jsで作ろうとすると、今度はサーバ側にNode.js
を求められてしまいます。(もちろんサーバ側が対応していればもっと恩恵を得られるようですが…)
サーバ側にNode.js
が無い場合に制作に使うのがVue-cli
と言う物のようです。
必要な開発環境
- Node.jsが使える開発環境(
nodebrew
npm
が使える前提で)- 個人的には
macOS
でHomebrew
をインストールしてからnodebrew
をインストール
- 個人的には
- 開発環境( 個人的には
IntelliJ IDEA
使ってます。 ) - ChromeブラウザとVueプラグイン(デバッグで結構使う)
開発環境にnpmでvue-cliを入れる
$ npm install -g @vue/cli
+ @vue/cli@4.1.1
$ npm install -g @vue/cli-service-global
+ @vue/cli-service-global@4.1.1
プロジェクトを作る
プロジェクトの作り方は、テンプレート的に覚えておいた方が楽です。
プロジェクト名は仮にmy-first-pwa
と名付けましょうか
$ vue create my-first-pwa
初っぱなにManually
を選ばないとPWAプロジェクトににならないので注意
Vue CLI v4.1.1
? Please pick a preset:
default (babel, eslint)
❯ Manually select features
Vue CLI v4.1.1
? Please pick a preset: Manually select features
? Check the features needed for your project:
◉ Babel
◯ TypeScript
◉ Progressive Web App (PWA) Support
❯◉ Router
◉ Vuex
◉ CSS Pre-processors
◉ Linter / Formatter
◯ Unit Testing
◯ E2E Testing
? Use history mode for router? (Requires proper server setup for index fallback
in production) (Y/n)
Workbox-cliを入れる
PWAを作る場合、service-worker.js
とか sw.js
とかを作成する必要がありますが、お手軽に作るならWorkbox
という物がありますので入れておいた方が楽です。
$ npm install workbox-cli --global
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
+ workbox-webpack-plugin@4.3.1
updated 1 package and audited 29251 packages in 8.042s
19 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
なんか core-js
が古いとかで怒られるのでとりあえず下記コマンドを…
$ npm install core-js@^3
$ workbox wizard
? What is the root of your web app (i.e. which directory do you deploy)? dist/
? Which file types would you like to precache? (Press <space> to select, <a> to toggle all, <i> to invert selection)css, ico, png, svg, html, js, json, txt
? Where would you like your service worker file to be saved? dist/service-worker.js
? Where would you like to save these configuration options? workbox-config.js
To build your service worker, run
workbox generateSW workbox-config.js
as part of a build process. See https://goo.gl/fdTQBf for details.
You can further customize your service worker by making changes to workbox-config.js. See https://goo.gl/gVo87N for details.
ビルドの際に自動的に service-worker.js
を生成させるために vue.config.js
を作成
module.exports = {
pwa: {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
swSrc: 'src/service-worker.js',
swDest: 'service-worker.js',
globPatterns: [
'**/*.{css,ico,png,html,js,json,webapp,txt}',
],
},
},
};
とりあえず…
大体ここまでで、アプリを作成できる状態になります。そのあたりはこの記事に加筆する予定です。読みづらい文章をよんでいただきありがとうございました。