4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

viteでmpa対応するために簡易プラグインを書いてみた

Last updated at Posted at 2022-02-21

結論

fast-globを使ってroot設定より下のファイルを調べてrollupOptionに突っ込む

input
Type: string | string [] | { [entryName: string]: string }
CLI: -i/--input

vite公式のドキュメントにはオブジェクトで指定されてますが、rollup configのinputの型について調べたところ、配列でも良さそうなため配列で指定

import { Plugin, UserConfig } from 'vite';
import fg from 'fast-glob';

// https://ja.vitejs.dev/config/#root
const generatePathConfig = (root = process.cwd()) => {
  const paths = fg.sync(`${root}/**/*.html`);
  return paths.map((path) => path.replace(root, ''));
};

const resolveMpaConfig = (vitePlugin: UserConfig): UserConfig => ({
  build: {
    rollupOptions: {
      input: generatePathConfig(vitePlugin.root)
    }
  }
})

//https://ja.vitejs.dev/guide/api-plugin.html#規約
export const vitePluginMpa: Plugin = {
  name: 'vite-plugin-mpa',
  config: (vitePlugin, _) => resolveMpaConfig(vitePlugin),
  apply: 'build'
}

/*
vitePluginMpa()として渡したい場合(拡張子指定など今後オプションが増えたらこっち?)
export const vitePluginMpa = (): Plugin  => ({
  name: 'vite-plugin-mpa',
  config: (vitePlugin, _) => resolveMpaConfig(vitePlugin),
  apply: 'build'
})
*/

import { defineConfig } from 'vite';
import path from 'path';
import { vitePluginMpa } from './mpa';

export default defineConfig({
    root: 'src',
    build: {
      outDir: '../dist',
      emptyOutDir: true,
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    plugins: [vitePluginMpa]
});

サンプル?
https://github.com/taka1156/p5.js-learning

ちょっとしたLPとかでmpaしたい時に使えるかな

(既にあるやつだと設定項目が多かったので勉強ついでに簡単なやつ書いてみました。)

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?