Viteで静的なLPサイトを開発する
前提の環境構築
ICS Mediaの「jQueryからTypeScript・Reactまで!Viteで始めるモダンで高速な開発環境構築」を参考に環境構築する。
TypeScriptを選択しても良かったが、ここでは、Vanilla JSで作成してる。
$ npm init vite@latest
テンプレートを選ぶよう指示されるので
> vanilla
を選択した。
root と outDir を設定する
root を設定する。
初期で作成される index.html がプロジェクトフォルダのルートにある構成は、将来的にゴッチャになっていきそうなので、以下の様な ./src に開発で編集するファイルが入ってる構成にしたい。
.
├── node_modules/
├── favicon.svg
├── package-lock.json
├── package.json
└── src/
├── index.html
└── main.js
公式docのrootの項目 を参考に root を./src に設定する。
1. vite.config.js を プロジェクトルートに作成する
2. vite.config.js を記述する。
以下の様に記述した。
module.exports = {
root: 'src'
}
3. 関係するファイルを移動する
srcディレクトリをつくって index.html と main.js を src/ に移した。
root config は index.html の位置を決定するものらしい。
outDir を設定する
npm run build や npm run serve を実行したときに この以下の様に ルート直下のdist フォルダにファイルが生成されて欲しい。
.
├── node_modules/
├── dist/
│ └── output files
├── favicon.svg
├── package-lock.json
├── package.json
├── src/
│ ├── index.html
│ └── main.js
└── vite.config.js
公式docのoutDirの項目 を参考にoutDir を../dist に設定する。
1. vite.config.js を以下の様に変更する。
module.exports = {
root: 'src',
build: {
outDir: '../dist'
}
}
ourDirの path は index.html が基準らしい
Mulit Page に対応する
LPサイトなので、1ページ毎にそれぞれのhtmlを書きたい。
Vite公式でサポートしてるMulti Page Appという機能を使えば実現できるらしい。
(要は、index.htmlとmain.js を1つのプロジェクトの中で複数作ってそれぞれ、Vite (rollup)でbuildするイメージか?)
vite.config.js で rollUpOptions を設定する
Viteは、ビルドにrollUpを使ってるため rollUpOtions を設定に書くらしい。
例えば、以下の様にsrc/privacy/ に プライバシーポリシーを表示するページを作成するとする。
.
├── node_modules/
├── dist/
│ └── output files
├── favicon.svg
├── package-lock.json
├── package.json
├── src/
│ ├── index.html
│ ├── main.js
│ └── privacy/
│ ├── index.html
│ └── main.js
└── vite.config.js
公式docの例 にそってその設定を書くとこうなる。
+const { resolve } = require('path')
+
+const root = 'src'
module.exports = {
- root: 'src',
+ root: root,
build: {
- outDir: '../dist'
+ outDir: '../dist',
+ rollupOptions: {
+ input: {
+ main: resolve(__dirname, root, 'index.html'),
+ privacy: resolve(__dirname, root, 'privacy/index.html')
+ }
+ }
}
}
If you specify a different root, remember that __dirname will still be the folder of your vite.config.js file when resolving the input paths. Therefore, you will need to add your root entry to the arguments for resolve.
vite-plugin-mpa がここらへんの設定を全部肩代わりしてくれそう。
public ディレクトリを設定する
index.html と同じ階層に public という名称のディレクトリを作ると、ビルド先にpublicの中身がそのまま出力される。
何が良いかっていうと、assetsファイルを絶対パスで指定できる。
configするためにはvite.config.js に publicDir : [index.htmlと同じディレクトリに作るディレクトリ名] を指定すれば良い
デフォルトでは、public だが、明示するために記載した。
const { resolve } = require('path')
const root = 'src'
module.exports = {
root: root,
+ publicDir: 'public',
build: {
outDir: '../dist',
rollupOptions: {
input: {
main: resolve(__dirname, root, 'index.html'),
privacy: resolve(__dirname, root, 'privacy/index.html')
}
}
}
}