【问题标题】:Spaces are gone in HTML after upgrading to vue-cli 3升级到 vue-cli 3 后,HTML 中的空格消失了
【发布时间】:2018-12-20 14:22:42
【问题描述】:

我使用 vue cli 2 没有任何自定义配置。现在我升级到 cli3,我注意到在处理后的 HTML 中它删除了所有空格。 例如如果我的原始 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>

注意&lt;span class... 之前的空格已消失,这会导致:

变成这样:

我的 vue.config.js 非常基础:

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

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

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

【问题讨论】:

  • vue-cli 中有an open issue,指的是this PR - 但它仍然没有合并。您可以手动合并,也可以使用preserveWhitespace: true

标签: webpack vue.js vue-cli


【解决方案1】:

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

您可以使用vue.config.js 文件将vue-loader 的模板编译器选项preserveWhitespace 配置为true

// 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;
      });
  }
};

【讨论】:

  • 这在 Vue 3 上不再适用。还有其他选择吗?
【解决方案2】:

@VamsiKrishna 答案工作正常,但自 vue-template-compiler 2.6 起已弃用 preserveWhitespace,您可以改用新选项 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';

【讨论】:

【解决方案3】:

其他答案适用于 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/

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2019-12-21
    • 2021-03-04
    • 2021-09-14
    • 2020-12-30
    • 1970-01-01
    • 2019-01-11
    • 2020-08-23
    相关资源
    最近更新 更多