升级到 vue-cli 3 后 HTML 中的空格消失了

Spaces are gone in HTML after upgrading to vue-cli 3

我使用的是 vue cli 2,没有任何自定义配置。现在我升级到 cli3,我注意到在处理的 HTML 中它删除了所有白色 space。 例如如果我原来的 html 是这样的:

<div class="link">
    <i class="fa fa-lg" :class="item.icon"/>
    <span class="hidden-sm hidden-xs">{{item.name}}</span>
</div>

旧的(cli 2 + webpack)会把它转换成这样:

<div class="link"><i class="fa fa-lg fa-calendar"/> <span class="hidden-sm hidden-xs">CALENDAR</span></div>

而新版本是这样做的:

<div class="link"><i class="fa fa-lg fa-calendar"/><span class="hidden-sm hidden-xs">CALENDAR</span></div>

注意 space 在 <span class... 之前消失了,这导致了这个:

变成这样:

我的 vue.config.js 很基础:

// vue.config.js
module.exports = {
  runtimeCompiler: true
}

我知道我可以添加 &nbsp; 或对 html 本身进行其他更改,但应用程序非常大,查找所有这些地方需要几天时间。

有人知道我需要哪些选项来确保它优化 html 与旧的 cli+webpack 组合一样吗?

由于@raina77ow 指出了问题的链接,preserveWhitespace 在 vue-loader 选项中默认为 false

您可以配置 vue-loader's template compiler option preserveWhitespace to true using the vue.config.js 文件

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        // modify the options...
        options.compilerOptions.preserveWhitespace = true;
        return options;
      });
  }
};

@VamsiKrishna 的回答很好,但是 preserveWhitespace 自 vue-template-compiler 2.6 以来已被弃用,您可以使用新选项 whitespace 代替:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        // modify the options...
        options.compilerOptions.whitespace = 'preserve';
        return options;
      });
  }
};

您可以检查其他选项和有效值here

Vue 3

在 Vue 3 上,您可以使用应用程序配置,这里是 docs:

const app = createApp({});

app.config.compilerOptions.whitespace = 'preserve';

其他答案在 Vue 2 上有效,但自 Vue 3 起无效。

从 Vue 版本 3.1.0 开始,现在可以在 vue-cli 中使用。

但使用不同的设置:只有在使用包含编译器和运行时的“完整”构建时才可能使用 compilerOptions,因此它支持即时编译模板。例如vue.global.jshttps://v3.vuejs.org/guide/installation.html#from-cdn-or-without-a-bundler

https://v3.vuejs.org/api/application-config.html#compileroptions

您可以在您定义应用程序的地方全局添加它(通常 main.js): app.config.compilerOptions.whitespace = 'preserve'

或在组件中 (https://v3.vuejs.org/api/options-misc.html#compileroptions):

export default {
  compilerOptions: {
    whitespace: 'preserve'
  }
}

而在 Vite 中(Vue 3.0.6 之后的版本):

vite.config.js

  plugins: [
    createVuePlugin({
      vueTemplateOptions: {
        compilerOptions: {
          whitespace: 'preserve'
        }
      }
    })
  ], // https://vitejs.dev/config/