0
0

Vue + Viteでビルド時に特定の属性を削除してビルドする方法

Posted at

目的

Webアプリケーションの開発においてテスト目的に付与した属性をプロダクションビルド時に剥がしたい場合があるかもしれません。
たとえばtesting-library/vue testing-libraryを用いてユニットテストを行なっていて、v-forで展開した配列の要素をdata-testidで別個取得できるように配列のIDを渡していたりする場合、あまり露出したくないなどあるかもしれません。
そういった場合のTipsです。

Vite Config

Viteでの開発やビルドの設定を行う vite.config.tsファイルでvueのプラグインの設定を調節します。

vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig(({ mode }) => ({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          nodeTransforms: [
            (node) => {
              if (mode === 'production') {
                if (node.type === 1) {
                  for (let i = 0; i < node.props.length; i++) {
                    if (node.props[i].name === 'data-testid') {
                      node.props.splice(i, 1);
                      i--;
                    }
                  }
                }
              }
            }
          ]
        }
      }
    }),
  ]
})

何をしているか

vueのビルドのために提供されているプラグインである@vitejs/plugin-vueはオプションを引数として渡すことができます。

@vitejs/plugin-vue
このオプションはvueのコアプラグインのDefinition fileを参照しています (@vue/compiler-sfc)
https://github.com/vuejs/core

その中でビルドするノードのタイプが1、HTML要素(ELEMENT)である場合にそのノードのpropsが6、HTML属性(ATTRIBUTE)である場合にその名称がdata-testidであれば削除しています。

これら一連の処理をビルドのモードがproductionの場合にのみ行うようにしています。

ちなみにモードはvite build --mode productionで渡すことができます。
渡していない場合はundefinedになります。

0
0
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
0
0