Problem

When loading TEI/XML files and visualizing them with JavaScript (Vue.js, etc.), there were cases where unintended whitespace was inserted.

Specifically, when writing HTML like the following:

<template>
  <div>
    お問い合わせは
    <a href="#">こちらから</a>
    お願いします
  </div>
</template>

It would render with unintended spaces: “お問い合わせは こちらから お願いします” as shown below.

A solution for this issue was published in the following repository:

https://github.com/aokiken/vue-remove-whitespace

However, I was unable to get it working in Nuxt 3 in my environment, so I used the source code as a reference and adapted it for Nuxt 3.

Below are my notes on this process.

Adapting for Nuxt 3

Create plugins/removeWhitespace.ts:

function isText(node: ChildNode) {
    return node.nodeType === Node.TEXT_NODE
}

function trimText(node: NodeListOf<ChildNode>) {
    Array.from(node).forEach((node) => {
        if (isText(node) && node.textContent) {
            node.textContent = node.textContent.trim()
            return
        }
        trimText(node.childNodes)
    })
}

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.directive("removeWhitespace", {
    mounted(el: HTMLElement) {
      trimText(el.childNodes)
    },
    updated(el: HTMLElement) {
      trimText(el.childNodes)
    },
  });
});

Then, use the v-remove-whitespace directive in pages/index.vue or similar files:

<template>
  <div v-remove-whitespace>
    お問い合わせは
    <a href="#">こちらから</a>
    お願いします
  </div>
</template>

As a result, the unintended whitespace was successfully removed.

Summary

My understanding of directives may be incomplete and there may be some inaccuracies, but I hope this serves as a useful reference.

Below are the source code and demo site (GitHub Pages).

Source Code

https://github.com/nakamura196/nuxt3-removeWhitespace

Demo Site

https://nakamura196.github.io/nuxt3-removeWhitespace/

As a side note, by writing nuxt.config.ts as follows, I was able to specify the baseURL:

export default defineNuxtConfig({
  app: {
    baseURL: "/nuxt3-removeWhitespace", // /<reponame>
  },
});

I hope this is also helpful as a reference for publishing Nuxt 3 SSG on GitHub Pages.