I have the following html code
<head>
<script src="https://unpkg.com/vue@3"></script>
<script defer src="script.js"></script>
</head>
<body>
<div id="main">
<div>
1. This is 1st line
2. This is 2nd line
3. This is 3rd line
</div>
<br>
<div style="white-space: pre-line;">
1. This is 1st line
2. This is 2nd line
3. This is 3rd line
</div>
</div>
</body>
Which will result in
1. This is 1st line 2. This is 2nd line 3. This is 3rd line
1. This is 1st line
2. This is 2nd line
3. This is 3rd line
However, when I mount a Vue instance onto my main div, this is the result I get
1. This is 1st line 2. This is 2nd line 3. This is 3rd line
1. This is 1st line 2. This is 2nd line 3. This is 3rd line
The code for Vue instance in the script.js file is as follow
const test = Vue.createApp({
}).mount("#main")
Why did my white-space style get ignored completely?
The Vue compiler collapses whitespace by default, so the newlines in your original code gets collapsed (extraneous whitespace is removed) to produce more efficient compiled output.
You can disable this globally in your example with app.config.compilerOptions.whitespace set to 'preserve':
const app = Vue.createApp({})
app.config.compilerOptions.whitespace = 'preserve'
app.mount("#main")
Or disable it per component:
const app = Vue.createApp({
compilerOptions: {
whitespace: 'preserve'
}
})
app.mount("#main")
Note: app.config.compilerOptions.whitespace is only respected when using the full build. Otherwise, you'd have to set the option through build flags.
You can configure @vue/compiler-sfc to disable whitespace-condense in this Vite config:
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
whitespace: 'preserve', ๐
},
},
}),
],
})
<br> where new-line is neededAlternatively, you could explicitly add <br> tags where needed, which would keep the originally intended optimization while implementing the desired spacing:
<div>
1. This is 1st line<br>
2. This is 2nd line<br>
3. This is 3rd line<br>
</div>